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

问题描述 投票:12回答:2

我在C#中使用Lookup类作为我的主要数据容器,供用户从两个Checked List框中选择值。

Lookup类比使用类Dictionary更容易使用,但是我找不到用于删除和向查找类添加值的方法。

我想过使用where和union,但我似乎无法正确使用它。

提前致谢。

linq c#-3.0 linq-to-objects lookup
2个回答
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);

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

添加和删​​除的一种方法是不断创建新的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);

要添加到列表中,我们可以执行以下操作:

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

2
投票

你可以做什么而不是使用LookUp类就是简单地使用它

var dictionary = new Dictionary<string, List<A>>(); 

其中A是您要映射到键的对象类型。我相信你知道如何添加和删除特定键的匹配对象组。 :)

© www.soinside.com 2019 - 2024. All rights reserved.