简体   繁体   English

使用LINQ将两个列表之间的值关联起来?

[英]Associate values between two lists with LINQ?

I have to List of items of same datamodel 我必须列出相同数据模型的项目

List A 清单A.

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

myList 我的列表

ID Name Address
1
2
3

i have to check the master list with the ID and get the other values from that list A for corresponding ID 我必须检查带有ID的主列表,并从该列表A中获取相应ID的其他值

How i can do this in linq c# 我如何在linq中做到这一点c#

You can do this in following way........... 你可以通过以下方式做到这一点...........

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

newList contain Person info which has id in myList............... newList包含在myList中具有id的Person信息...............

This will give you all the values from List A for all the ids that are in myList: 这将为列表A中的myList中的所有id提供所有值:

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

you can do this by linq as below: 您可以通过linq执行此操作,如下所示:

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

Efficient way is sorting and comparing elements, which is O(n logn) and if elements in both list are sorted it's O(n): 有效的方法是排序和比较元素,即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;
   }
}

in your controller, pass the id 在你的控制器中,传递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

}

Hope this gives you direction. 希望这会给你指路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM