Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values from one list to another using LINQ

Hello I have a little problem with assigning property values from one lists items to anothers. I know i could solve it "the old way" by iterating through both lists etc. but I am looking for more elegant solution using LINQ.

Let's start with the code ...

class SourceType
{
    public int Id;
    public string Name;
    // other properties
}

class DestinationType
{
    public int Id;
    public string Name;
    // other properties
}

List<SourceType> sourceList = new List<SourceType>();
sourceList.Add(new SourceType { Id = 1, Name = "1111" });
sourceList.Add(new SourceType { Id = 2, Name = "2222" });
sourceList.Add(new SourceType { Id = 3, Name = "3333" });
sourceList.Add(new SourceType { Id = 5, Name = "5555" });

List<DestinationType> destinationList = new List<DestinationType>();
destinationList.Add(new DestinationType { Id = 1, Name = null });
destinationList.Add(new DestinationType { Id = 2, Name = null });
destinationList.Add(new DestinationType { Id = 3, Name = null });
destinationList.Add(new DestinationType { Id = 4, Name = null });

I would like to achieve the following:

  • destinationList should be filled with Names of corresponding entries (by Id) in sourceList
  • destinationList should not contain entries that are not present in both lists at once (eg. Id: 4,5 should be eliminated) - something like inner join
  • I would like to avoid creating new destinationList with updated entries because both lists already exist and are very large, so no "convert" or "select new".

In the end destinationList should contain:

1 "1111"
2 "2222"
3 "3333"

Is there some kind of elegant (one line Lambda? ;) solution to this using LINQ ?

Any help will be greatly appreciated! Thanks!

like image 345
user1269810 Avatar asked Mar 14 '12 18:03

user1269810


2 Answers

I would just build up a dictionary and use that:

Dictionary<int, string> map = sourceList.ToDictionary(x => x.Id, x => x.Name);

foreach (var item in destinationList)
    if (map.ContainsKey(item.Id))
        item.Name = map[item.Id];

destinationList.RemoveAll(x=> x.Name == null);
like image 164
BrokenGlass Avatar answered Sep 23 '22 23:09

BrokenGlass


Hope this will your desired result. First join two list based on key(Id) and then set property value from sourceList.

        var result = destinationList.Join(sourceList, d => d.Id, s => s.Id, (d, s) =>
        {
            d.Name = s.Name;
            return d;
        }).ToList();
like image 44
Towhidul Islam Tuhin Avatar answered Sep 25 '22 23:09

Towhidul Islam Tuhin