views:

43

answers:

1

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.

+1  A: 

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);
Ray Booysen
The removing works, can you please let me know how to add items to the lookup list.Please let me know if it is possible to add and remove items to the inner list.
Ahmad Hajou
just added, let me know what you think
Ray Booysen
It Works, thanks alot. I guess as far as removing data from the inner list the process is easy, since now I have a list before the ToLookup method call.
Ahmad Hajou