2012-03-11 47 views
2

我必須列出相同的數據模型的項目兩個列表與LINQ之間的關聯值?

列表A

ID Name Address 
1 aaa address1 
2 bbb address2 
3 ccc address3 

myList中

ID Name Address 
1 
2 
3 

我與ID檢查主列表,並獲得其他來自該列表A的值對應ID

我怎麼能在你的控制器LINQ的C#

+0

告訴我們你有什麼到目前爲止 – 2012-03-11 08:32:21

回答

4

您可以按以下方式做到這一點...........

List<Person> newList = (from master in listMaster 
         from list in myList 
         where master.id == list.id 
         select master).ToList<Person>(); 

newList含有在myList中的ID人物信息...............

+0

您可以省略「ToList」中的類型 – 2012-03-11 08:53:48

+0

謝謝您計算出來.... – 2012-03-11 09:01:06

0

做到這一點,通過ID

public ActionResult ListController(int id) 
{ 
    //process code 

    //syntax would be database.items.Select(list => list.ID = id) for checking with the master list for corresponding IDs 

} 

希望這給你方向。

2

這會給你由A組的所有值全部都在myList中的ID:

var res = from a in ListA 
where myList.contains(a.ID) 
select a 
+0

當然可以,但「獲取其他值...爲相應的ID」 – 2012-03-11 08:50:15

+0

我認爲「其他值」是指名稱和地址,並且這應該對myList中的所有ID執行 – 2012-03-11 08:57:25

2

您可以通過LINQ如下做到這一點:

myList = myList.Select(x=>listA.FirstOrDefault(y=>y.ID == x.ID)??x).ToList() 

有效的方法是進行排序和比較的元素,這是O(n LOGN),如果在這兩個列表中的元素進行排序是O(N):

listA = listA.OrderBy(x=>x.ID).ToList(); 
myList = myList.OrderBy(x=>x.ID).ToList(); 

int index = 0; 
foreach(var item in listA) 
{ 
    while(index < myList.Count && myList[index].ID < listA.ID) 
     index++; 
    if (index > myList.Count) 
    break; 

    if (myList[index].ID = item.ID) 
    { 
     myList[index] = item; 
    } 
}