Can not implicit convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'

1

I have the following method below for the purpose of returning notifications that should be displayed for a given client and notifications that should be served to all clients.

public List<TNotification> GetNotifications(TClient client)
{
    var notificacoesClient = Session.CreateCriteria<TNotification>()
        .CreateAlias("TClientNotifications", "clientNotifications", JoinType.LeftOuterJoin)
        .SetFetchMode("clientNotifications.Client", FetchMode.Eager)
        .CreateAlias("clientNotifications.Client", "client", JoinType.LeftOuterJoin)
        .Add(Restrictions.Eq("client.Id", client.Id))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>()
        .ToList();

    var notificacoesAll = Session.CreateCriteria<TNotification>()
        .Add(Restrictions.Eq("IsToAll", true))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>()
        .ToList();

    return notificacoesAll.Union(notificacoesClient);
}

However, the return notificacoesAll.Union(notificacoesClient); statement is returning the following message:

  

Can not implicity convert type   'System.Collections.Generic.IEnumerable'   to 'System.Collections.Generic.List'.   An explicit conversion exists (are you missing a cast?)

How could you resolve this issue?

    
asked by anonymous 14.12.2016 / 11:59

2 answers

5

This error happens because notificacoesAll.Union(notificacoesClient) returns a IEnumerable<TNotification> , but the signature of your method expects List<TNotification> .

So you have two alternatives:

  • Change your method signature to return IEnumerable<TNotification>
  • Transform the result of your union into a list:

    return notificacoesAll.Union(notificacoesClient).ToList();
    

One more detail: I do not think it's necessary to call ToList in the queries of your example, because List already returns a list (it's redundant).

    
14.12.2016 / 12:18
2

Take out .ToList() from the list and let only return

Something like this:

public List<TNotification> GetNotifications(TClient client)
{
    var notificacoesClient = Session.CreateCriteria<TNotification>()
        .CreateAlias("TClientNotifications", "clientNotifications", JoinType.LeftOuterJoin)
        .SetFetchMode("clientNotifications.Client", FetchMode.Eager)
        .CreateAlias("clientNotifications.Client", "client", JoinType.LeftOuterJoin)
        .Add(Restrictions.Eq("client.Id", client.Id))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>();

    var notificacoesAll = Session.CreateCriteria<TNotification>()
        .Add(Restrictions.Eq("IsToAll", true))
        .AddOrder(Order.Desc("Id"))
        .List<TNotification>();

    return notificacoesAll.Union(notificacoesClient).ToList();
}
    
14.12.2016 / 12:20