Ahm*_*jou 12 linq lookup linq-to-objects c#-3.0
我在C#中使用Lookup类作为我的主要数据容器,供用户从两个Checked List框中选择值.
Lookup类比使用类Dictionary更容易使用,但是我找不到用于删除和向查找类添加值的方法.
我想过使用where和union,但我似乎无法正确使用它.
提前致谢.
Ray*_*sen 14
不幸的是,Lookup类的创建是.NET框架的内部.创建查找的方式是通过Lookup类上的静态工厂方法.这些是:
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);
Run Code Online (Sandbox Code Playgroud)
但是,这些方法是内部的,不供我们消费.查找类没有任何删除项目的方法.
添加和删除的一种方法是不断创建新的ILookup.例如 - 如何删除元素.
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);
Run Code Online (Sandbox Code Playgroud)
要添加到列表中,我们可以执行以下操作:
//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);
Run Code Online (Sandbox Code Playgroud)