2012-11-27 198 views
-2

我有一个问题在一个查询两个列表合并:LINQ的名单列表

public class Class1 { 
    public int id { get; set; } 
    public List<Class2> attr { get; set; } 
} 

public class Class2 { 
    public int id { get; set; } 
} 

我的查询看起来像这样:

var q = (from m in context.table 
       select new Class1 
       { 
        id = m.ID, 
        attr = (from t in context.table2 
           where m.id == t.id 
           select new Class2 { 
            id= t.id 
           }).Take(5).ToList() 
       }).Take(1).ToList(); 

的任何解决方案,这个问题?

问题: 我的问题是,我的结果始终为空。如果我删除第二个查询

     attr = (from t in context.table2 
           where m.id == t.id 
           select new Class2 { 
            id= t.id 
           }).Take(5).ToList() 

,我的查询工作!

+0

这里有什么问题? – ryadavilli

+0

是什么问题?任何错误信息? –

+1

我很抱歉我的问题。我是这个论坛的新成员。 – Calimero

回答

1

下面的代码完美地工作(我换成你context变量,我自定义的),所以,在我看来,你最好检查你的where声明

using System.Linq; 
using System.Collections.Generic; 

namespace ConsoleApplication1 
{ 
    public class Class1 
    { 
     public int id { get; set; } 
     public List<Class2> attr { get; set; } 
    } 

    public class Class2 
    { 
     public int id { get; set; } 
    } 

    class MyEntity 
    { 
     public int ID { get; set; } 
     public MyEntity(int id) 
     { 
      ID = id; 
     } 
    } 
    class MyContext : List<MyEntity> 
    { 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 

      var context = new MyContext(); 
      context.Add(new MyEntity(1)); 
      context.Add(new MyEntity(2)); 
      context.Add(new MyEntity(3)); 
      context.Add(new MyEntity(4)); 
      context.Add(new MyEntity(5)); 

      var q = (from m in context 
        select new Class1 
        { 
         id = m.ID, 
         attr = (from t in context 
           where m.ID == t.ID 
           select new Class2 
           { 
            id = t.ID 
           }).Take(5).ToList() 
        }).Take(1).ToList(); 
     } 
    } 
} 
0

你可以尝试这样的事情: -

var listAB = listA.Cast<object>().Union(listB.Cast<object>()).ToLookup(x => x is TypeA ? (x as TypeA).Key : (x as TypeB).Key) 
      .Select(kv => { 
       var a = kv.FirstOrDefault(x => x is TypeA) as TypeA; 
       var b = kv.FirstOrDefault(x => x is TypeB) as TypeB; 
       return new TypeAB() { 
        Key = kv.Key, 
        ValueA = a != null ? (int?)a.Value : null, 
        ValueB = b != null ? (int?)b.Value : null 
       }; 
      }).ToList(); 
0

我发现了灵魂。而不是使用列表<>我将其更改为IQueryable <>现在它可以工作。

我记得我的错误信息:“LINQ到实体无法识别方法列表... LINQ这种方法不能被翻译成店表达”

没有人明白了吗?