2

I have three lists, BeforeList, AfterList and FinalList

BeforeList has the following values

ID Description Operation
1  Descr1      Null
2  Descr2      Null
3  Descr3      Null

AfterList has the following values

ID Description Operation
1  Descr1      Null
2  DescrC      Null
4  Descr4      Null

My FinalList would be

ID Description Operation
1  Descr1      Null
2  DescrC      Update
3  Descr3      Delete
4  Descr4      Add

How do I get the FinalList using LINQ

Bala R
  • 107,317
  • 23
  • 199
  • 210
Gansun
  • 301
  • 2
  • 7
  • 15

3 Answers3

3

How about something like:

var beforeListById = beforeList.ToDictionary(item => item.Id); 
var afterListById = afterList.ToDictionary(item => item.Id); 

var finalResult = from id in beforeListById.Keys.Union(afterListById.Keys)

                  let before = beforeListById.ContainsKey(id) ? beforeListById[id] : null
                  let after = afterListById.ContainsKey(id) ? afterListById[id] : null

                  select new Record
                  {
                      Id = id,
                      Description = (after ?? before).Description,
                      Operation = (before != null && after != null) 
                                   ? (after.Description == before.Description ? "Null" : "Update")
                                   : (after != null) ? "Add" : "Delete"
                  };

EDIT: Made query simpler (assuming items are non-null).

Ani
  • 111,048
  • 26
  • 262
  • 307
1

This is a simple implementation, but you could try something like this:

var differences = listA.Where(a => !listB.Any(b => b.id == a.id)).Union(listB.Where(b => !listA.Any(a => a.id == b.id)));

EDIT

According to MSDN, you can just use Union to merge the two lists, and duplicates will be filtered out by default. If not, you can always call Distinct():

List<Something> = beforeList.Union(afterList).ToList();
James Johnson
  • 45,496
  • 8
  • 73
  • 110
0

Looks like you need distinct union on your lists. Here there was a discussion about unions which could give an example of a syntax: Linq to entities : Unions + Distinct

Community
  • 1
  • 1
ElDog
  • 1,230
  • 1
  • 10
  • 21