User987 User987 - 1 month ago 13
ASP.NET (C#) Question

Adding missing items to collection using LINQ

I have two collections from different classes that have these two commpon properties:

public class Class1
{
public string ItemID {get;set;}
public int sales {get;set;}
}

public class Class2
{
public string ItemID {get;set;}
}


Now what happens here I have two collections with these types of classes like this:

List<Class1> list1; // has items that actually have sales...

List<Class1> list2; // has all items that have or don't have sales


list1
is missing items that don't have sales at all. And what I would like to do here is somehow compare these two lists by the
itemID
, and if the
itemID
is missing, then I'm gonna add the missing item to
list1
with setting property
sales
to 0 manually.

And when the missing item is found, then i'd like to do this:

list1.Add(new Class1
{
Sales = 0,
ItemID = ItemID,
});


Or some other way to add the missing items and setting their property
sales
to 0...

Can someone help me out?

Edit:

Guys I think i hve more explaining to do... So basically if the ItemID from Class2 list isn't present in Class1 list, then it's added to Class1 list with property "Sales" set to 0....

Answer Source

You can try

var missingItems = 
    list2.Where(class2 => list1.Any(class1 => class1.ItemId == class2.ItemId) == false)
         .Select(class2 => new Class1 
         { 
             ItemId = class2.ItemId, 
             Sales = 0 
         });

list1.AddRange(missingItems);

For better performance of Where clause your can create HashSet<string> of list1.

var existedIds = new HashSet<string>(list1.Select(class1 => class1.ItemId));
var missingItems = 
    list2.Where(class2 => existedIds.Contains(class2.ItemId) == false)
         .Select(class2 => new Class1 
         { 
             ItemId = class2.ItemId, 
             Sales = 0 
         }); 

list1.AddRange(missingItems);