Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# / .NET comparing two large lists and finding missing items from both list

Tags:

c#

linq

so basically I have two large lists like following:

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


var oldList = new List<Items>(); // oldList

var newList = new List<Items>(); // new list

Both lists are very large, and a simple double foreach wouldn't be sufficient due to poor execution time if they are both large (more than 30 seconds).

In previous question that I've asked on stackoverflow I got a reply on how to compare these two same lists and find out which items have different QuantitySold parameter, and then store it in a third list called "DifferentQuantityItems" like following:

var differentQuantityItems =
    (from newItem in newList
     join oldItem in oldList on newItem.ItemID equals oldItem.ItemID
     where newItem.QuantitySold != oldItem.QuantitySold
     select newItem).ToList();

Now what I would like to get from these two lists is following:

- A list of items that are present in newList, but not in oldList

- A list of items that are present in oldList, but not in newList

How can I achieve this ? Can someone help me out?

P.S. The way I would "know" that either item is missing from one of the lists is by property "ItemID"...

like image 844
User987 Avatar asked Mar 13 '19 13:03

User987


2 Answers

Edited

Except will work much faster. Here you can read aboud it's perfomance

var missedOld = oldList.Except(newList, new ItemsEqualityComparer());
var oldList= oldList.Except(missedOld, new ItemsEqualityComparer());

Old answer

Two different lists with missing items

var missedOld = oldList.Where(x => !newList.Select(i => i.ItemID).Contains(x.ItemID)) 
var missedNew = newList.Where(x => !oldList.Select(i => i.ItemID).Contains(x.ItemID))

All missed items in one list:

oldList.Concat(newList).GroupBy(x => x.ItemID).Where(x => x.Count() < 2).Select(x => x.Value).ToList()
like image 186
Akmal Salikhov Avatar answered Nov 07 '22 12:11

Akmal Salikhov


Have you considered converting your lists to hashsets and using the Except method ?

See Difference between two lists

And:Is there a way to get the difference between two sets of objects in c#

like image 30
Pierre Avatar answered Nov 07 '22 13:11

Pierre