C# System.Linq.Lookup Class Removing and Adding values
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.
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);
what you can do instead of using a LookUp class is to simply use this
var dictionary = new Dictionary<string, List<A>>();
where A is the object type you want to map to the key. i trust you know how to add and delete the group of matched objects to a specific key. :)
精彩评论