有没有什么优雅的方法
IDictionary<int, IEnumerable<int>> ILookup<int,int>?据我所知,它应该是相同的,但我发现查找更清楚。
这背后的故事更复杂,但我不得不选择is列表及其相关is列表:
masters
.Select(m => new {masterId = m.Id, childIds = m.Children.Select(c => c.Id)})
.ToDictionary(k => masterId, v => v.childIds)我很乐意直接选择查找,但我不知道是否可能。
主变量类型的示例可以很简单,如下所示:
public class Master
{
public int Id { get; set; }
public List<Master> Children { get; set; }
}发布于 2015-09-30 13:59:00
正如LasseV.Karlsen在注释中所建议的,您可以创建一个公开ILookup的包装器类型
public class LookupDictionary<TKey, TElement> : ILookup<TKey, TElement>
{
private readonly IDictionary<TKey, IEnumerable<TElement>> _dic;
public LookupDictionary(IDictionary<TKey, IEnumerable<TElement>> dic)
{
_dic = dic;
}
public int Count
{
get { return _dic.Values.Sum(x => x.Count()); }
}
public IEnumerable<TElement> this[TKey key]
{
get { return _dic.ContainsKey(key) ? _dic[key] : Enumerable.Empty<TElement>(); }
}
public bool Contains(TKey key)
{
return _dic.ContainsKey(key);
}
public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
{
return _dic.Select(kv => new LookupDictionaryGrouping(kv)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
class LookupDictionaryGrouping : IGrouping<TKey, TElement>
{
private KeyValuePair<TKey, IEnumerable<TElement>> _kvp;
public TKey Key
{
get { return _kvp.Key; }
}
public IEnumerator<TElement> GetEnumerator()
{
return _kvp.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public LookupDictionaryGrouping(KeyValuePair<TKey, IEnumerable<TElement>> kvp)
{
_kvp = kvp;
}
}
}发布于 2015-09-30 13:10:25
那么,您可以将字典压平,然后将其转换为Lookup。
dict.SelectMany(kvp -> kvp.Value, (kvp, v) => new {k = kvp.Key, v})
.ToLookup(kvp => kvp.k, kvp => kvp.v)但实际上它和字典是一样的,所以似乎没有必要。
发布于 2015-09-30 13:17:38
如果我对你的理解正确,你想把你的收藏整理成平版。你可以这样做:
masters.SelectMany(x => x.Children, (x, y)
=> new {
ParentId = x.Id,
ChildId = y.Id
})
.ToLookup(x => x.ParentId, y => y.ChildId);这样你就能拿到你的ILookup<int,int>了。此外,您不需要任何Dictionary集合。但是使用Dictionary是很安全的。
https://stackoverflow.com/questions/32866792
复制相似问题