2012-08-09 202 views
0

我目前正在努力收集關於我的對象集合LINQ查詢分組:人,汽車LINQ嵌套多個集合

每個人都可以擁有多輛。

我想選擇所有人在這個人擁有的人和所有組的所有車輛。我寫到目前爲止的查詢是:

from c in persons,d in cars 
    where c.id = d.ownerID 
    group by c.Firstname into MG = tolist() 

但它只返回有車的人。如果一個人沒有車,他就不在列表中。我無法用正確的邏輯來彌補。

回答

1

嘗試:

List<person> plist = new List<person>(); 
     plist.Add(new person(1, "a")); 
     plist.Add(new person(2, "b")); 
     plist.Add(new person(3, "c")); 
     plist.Add(new person(4, "d")); 

     List<cars> clist = new List<cars>(); 
     clist.Add(new cars(1, "c1")); 
     clist.Add(new cars(1, "c2")); 
     clist.Add(new cars(1, "c5")); 
     clist.Add(new cars(2, "c1")); 
     clist.Add(new cars(3, "c1")); 
     clist.Add(new cars(3, "c5")); 
     clist.Add(new cars(3, "c3")); 
     clist.Add(new cars(3, "c2")); 
     clist.Add(new cars(4, "c2")); 
     clist.Add(new cars(4, "c5")); 


     var result = from p in plist 
       join c in clist on p.id equals c.ownerID into k 
       from s in k.DefaultIfEmpty() 
       select new { p.firstName , carName = (s == null ? String.Empty :s.name)}; 

string sss = ""; 
foreach (var v in result) 
{ 
     sss+= (v.firstName + " : " + v.carName + " >> "+"\n"); 
} 
textBox1.Text = sss; 

和類:

class person 
{ 
    public int id; 
    public string firstName; 

    public person(int id1, string name) 
    { 
     id = id1; 
     firstName = name; 
    } 
} 

class cars 
{ 
    public int ownerID; 
    public string name; 

    public cars(int id,string name1) 
    { 
     ownerID = id; 
     name = name1; 
    } 
} 
+0

Thnank你的邏輯。現在更有意義。 – 2012-08-10 02:57:54

+0

hi @ jas-sra,享受。 – 2012-08-10 04:36:13