2012-11-27 197 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這種方法不能被翻譯成店表達」

沒有人明白了嗎?