C#System.Linq.Lookup类删除和添加值

问题描述:

我使用C#中的Lookup类作为我的主数据容器,供用户从两个Checked List框中选择值。C#System.Linq.Lookup类删除和添加值

Lookup类远比使用类Dictionary>更容易使用,但是我无法找到将值移除并添加到查找类的方法。

我想过使用哪里和工会,但我似乎无法做到正确。

在此先感谢。

+0

你为什么不建立自己的youre查找执行?基于字典,不应超过几行代码。 – leppie 2010-10-27 08:13:10

+0

这里同意leppie。查找类仅用于查找数据,而不是修改它。再加上字典不是太难使用,可能会很好,只是在字典的顶部写封装。 – 2010-10-27 08:57:17

+0

查找还有一个不同的机制来对字典进行实际查找。但是通过一些简单的测试,它们都表现得非常快。 – 2010-10-27 09:01:59

不幸的是,查找类的创建是.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); 

但是,这些方法是内部的,不适合我们消费。查找类没有任何删除项目的方法。

你可以做一个添加和删除的方法是不断创建新的ILookups。例如 - 如何删除一个元素。

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); 

用于添加到列表中,我们可以做这样的事情:

//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); 
+0

删除作品,请你让我知道如何将项目添加到查找列表。 请让我知道是否有可能添加和删除项目到内部列表。 – 2010-10-27 08:14:14

+0

刚刚添加,让我知道你在想什么 – 2010-10-27 08:47:15

+0

它的工作原理,非常感谢。我想尽可能从内部列表中删除数据,这个过程很简单,因为现在我在ToLookup方法调用之前有一个列表。 – 2010-10-27 09:19:36