Search code examples
c#.netlistunionselectlistitem

Do a correct union on two List<SelectListItem>


retval.AddRange(oldList.Union(newList));

Both the oldList and newList are declared here

List<SelectListItem> oldList = new List<SelectListItem>();
List<SelectListItem> newList = new List<SelectListItem>();

I want to union these two lists, removing duplicate items that have the same "text" property. If there is a dupe between newList and oldList on the text property, it should keep the text/value pair of the newList.

The above union doesn't seem to be doing anything besides concat'ing the lists almost, don't know why.

What am I doing wrong?


Solution

  • I want to union these two lists, removing duplicate items that have the same "text" property.

    The Union method will not handle this requirement. You could do this via:

    retVal.AddRange(newList); // Since you want to keep all newList items, do this first
    
    // Add in all oldList items where there isn't a match in new list
    retVal.AddRange(oldList.Where(i => !newList.Any(n => i.Text == n.Text)));