C# System.Linq.Lookup Class Removing and Adding values

Ahmad Hajou picture Ahmad Hajou · Oct 27, 2010 · Viewed 19.1k times · Source

I'm using Lookup class in C# as my prime data container for the user to select values from two Checked List boxes.

The Lookup class is far easier to use than using the class Dictionary>, however I cannot find methods for removing and adding values to a lookup class.

I thought about using the where and the union, but i cant seem to get it right.

Thanks in advance.

Answer

Ray Booysen picture Ray Booysen · Oct 27, 2010

Unfortunately the creation of the Lookup class is internal to the .NET framework. The way that the lookup is created, is via static Factory Methods on the Lookup class. These are:

internal static Lookup<TKey, TElement> Create<TSource>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer);
    internal static Lookup<TKey, TElement> CreateForJoin(IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IEqualityComparer<TKey> comparer);

However, these methods are internal and not for consumption by us. The lookup class does not have any way of removing items.

One way you could do an add and remove is to constantly create new ILookups. For example - how to delete an element.

public class MyClass
{
  public string Key { get; set; }
  public string Value { get; set; }
}

//We have a fully populated set:
var set = new List<MyClass>() //Populate this.
var lookup = set.ToLookup(m => m.Key, m => m);

//Remove the item where the key == "KEY";
//Now you can do something like that, modify to your taste.
lookup = lookup
  .Where(l => !String.Equals(l.Key, "KEY"))
   //This just flattens the set - up to you how you want to accomplish this
  .SelectMany(l => l)
  .ToLookup(l => l.Key, l => l.Value);

For adding to the list, we could do something like this:

//We have a fully populated set:
var set = new List<MyClass>() //Populate this.
var lookup = set.ToLookup(m => m.Key, m => m);

var item = new MyClass { Key = "KEY1", Value = "VALUE2" };

//Now let's "add" to the collection creating a new lookup
lookup = lookup
  .SelectMany(l => l)
  .Concat(new[] { item })
  .ToLookup(l => l.Key, l => l.Value);