Iva*_*čin 39 .net c# collections
我有List<IGrouping<string,string>>.
是否有可能在此列表中添加新项目?或者实际上,是否可以创建一些IGrouping对象?
Nat*_*son 58
如果你真的想创建自己的IGrouping<TKey, TElement>,它是一个简单的实现接口:
public class MyGrouping<TKey, TElement> : List<TElement>, IGrouping<TKey, TElement>
{
public TKey Key
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
该类继承List<T>并实现IGrouping接口.除了作为IEnumerable和IEnumerable<TElement>(List<T>满足)的要求之外,唯一要实施的财产是Key.
从这里你可以创建MyGrouping<string, string>你想要的所有s并将它们添加到你的List<IGrouping<string,string>>.
Ani*_*Ani 10
从.NET 4.0开始,BCL中似乎没有任何实现该接口的公共类型IGrouping<TKey, TElement>,因此您无法轻松地"新建一个".
当然,没有什么可以阻止你:
IGrouping<TKey, TElement>从一个LINQ查询,如ToLookup与GroupBy和增加它/它们到您的列表.ToList()现有的组序列(来自ToLookup/GroupBy).例:
IEnumerable<Foo> foos = ..
var barsByFoo = foos.ToLookup(foo => foo.GetBar());
var listOfGroups = new List<IGrouping<Foo, Bar>>();
listOfGroups.Add(barsByFoo.First()); // a single group
listOfGroups.AddRange(barsByFoo.Take(3)); // multiple groups
Run Code Online (Sandbox Code Playgroud)
不过,目前尚不清楚为什么要这样做.
您还可以通过不对列表中的内容进行分组来破解分组:
var listOfGroups = new[] { "a1", "a2", "b1" }
.GroupBy(x => x.Substring(0, 1))
.ToList();
// baz is not anything to do with foo or bar yet we group on it
var newGroup = new[] { "foo", "bar" }.GroupBy(x => "baz").Single();
listOfGroups.Add(newGroup);
Run Code Online (Sandbox Code Playgroud)
listOfGroups 然后包含:
a:
a1, a2
b:
b1
baz:
foo, bar
Run Code Online (Sandbox Code Playgroud)
IGrouping<TKey, TElement> CreateGroup<TKey, TElement>(IEnumerable<TElement> theSeqenceToGroup, TKey valueForKey)
{
return theSeqenceToGroup.GroupBy(stg => valueForKey).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)