2012-03-11 57 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; 
    } 
}