Home > Net >  Replace a list item value with another list item value based on multiple condition
Replace a list item value with another list item value based on multiple condition

Time:05-30

I have two list. ListA and ListB.

ListA

ID  Name    Age
001 Andy    null
002 Sam     null

ListB

ID  Name    Age
001 Andy    10

What I want to do is replace ListA's Age with ListB'Age based on two conditions using Linq. They are

ListA.ID == ListB.ID 
ListA.Name == ListB.Name

So, the final result would be:

ID  Name    Age
001 Andy    10
002 Sam     null

Please ignore column names because they are only for demo purpose.

CodePudding user response:

You can work with Linq, the concept is listA LEFT JOIN listB.

var result = (from a in listA
            join b in listB on new { a.ID, a.Name } equals new { b.ID, b.Name } into ab
            from b in ab.DefaultIfEmpty()
            select new People
            {
                ID = a.ID,
                Name = a.Name,
                Age = b?.Age
            }
        ).ToList();

Sample .NET Fiddle

CodePudding user response:

Given two list of items

List<ListItem> listA = new List<ListItem>();
List<ListItem> listB = new List<ListItem>();

of this type

    public class ListItem 
    {
        public string ID { get; set; }
        public string Name { get; set; }

        public int? Age { get; set; }
    }

you can change all listA Age values this way:

listA.ForEach(item => 
    item.Age = listB.Where(itemB => itemB.ID == item.ID && itemB.Name == item.Name)
    .FirstOrDefault()?.Age);

CodePudding user response:

using foreach and linq

public class emp
{
    public string ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

static void Main(string[] args)
{

    var ListA = new List<emp>();
    var ListB = new List<emp>();

    ListA.Add(new emp { ID = "001", Name = "Andy" });
    ListA.Add(new emp { ID = "002", Name = "Sam" });

    ListB.Add(new emp { ID = "001", Name = "Andy", Age = 10 });

    foreach (var emp in ListA)
    {
        var empfound = ListB.FirstOrDefault(lista => lista.ID == emp.ID);
        if (empfound != null) emp.Age = empfound.Age;
    }
}
  • Related