Spen D
Spen D

Reputation: 4345

Associate values between two lists with LINQ?

I have to List of items of same datamodel

List 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

How i can do this in linq c#

Upvotes: 2

Views: 1662

Answers (4)

user1082916
user1082916

Reputation:

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...............

Upvotes: 4

Saeed Amiri
Saeed Amiri

Reputation: 22555

you can do this by linq as below:

 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):

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;
   }
}

Upvotes: 2

A.B.Cade
A.B.Cade

Reputation: 16905

This will give you all the values from List A for all the ids that are in myList:

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

Upvotes: 2

user5398447
user5398447

Reputation:

in your controller, pass the 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.

Upvotes: 0

Related Questions