Linq在C#中使用IEnumerable

时间:2013-03-05 09:12:49

标签: linq

显然,如果使用以下代码,则会出错。它说:

  

无法将System.Linq.IQueryable<AnonymousType>转换为System.Collection.Generic.IEnumerable

请告知我如何解决这个问题?

public IEnumerable<Session> GetAllListDetailConsumer(string refId)
{
    ObjectQuery<Session> sessions = db.Sessions;
    ObjectQuery<SessionsList> sessionsLists = db.SessionsList;
    var query =
        from s in sessions
        join sList in sessionsLists on s.ReferralListID equals sList.ReferralListID
        where s.ReferralListID == new Guid(refId)
        select new SessionConsumerList
        {
            ReferralListID = s.ReferralListID,
            SessionServerId = s.SessionServerID,
            ApplicationID = s.ApplicationID,
            // ...
            ConsumerID = sList.ConsumerID,
            ConsumerFirstName = sList.ConsumerFirstName,
            ConsumerFamilyName = sList.ConsumerFamilyName,
            // ...
        };
    return query.ToList();
}

2 个答案:

答案 0 :(得分:3)

您正在使用select new进行选择,这会创建anonymous type,您需要在查询中投放到Session类,例如。

select new Session
{
....

但请记住,如果您的Session类是表示数据库/数据上下文中的表,那么您不能投影到该类,而是可能必须创建一个临时类并将选择项目投影到该类类。

编辑 (由于现在已经编辑了问题)

现在您选择的是new SessionConsumerList并且您要返回IEnumerable<Session>,您需要修改方法签名才能返回IEnumerable<SessionConsumerList>

答案 1 :(得分:0)

为什么不在另一种方法中分离SessionConsumerList的创建?使代码更清洁。像这样:

public static SessionConsumerList CreateSessionConsumerList(
    Session s,
    SessionsList sList)
{
    return new SessionConsumerList
    {
        ReferralListID = s.ReferralListID,
        SessionServerId = s.SessionServerID,
        ApplicationID = s.ApplicationID,
        // ...
        ConsumerID = sList.ConsumerID,
        ConsumerFirstName = sList.ConsumerFirstName,
        ConsumerFamilyName = sList.ConsumerFamilyName,
        // ...
    };
}

然后:

var query =
    from s in sessions
    join sList in sessionsLists on s.ReferralListID equals sList.ReferralListID
    where s.ReferralListID == new Guid(refId)
    select CreateSessionConsumerList(s, sList);