Skip to main content
 首页 » 编程设计

c#之如何直接返回 ILookup(不使用 Dictionary->ILookup 转换器)

2024年02月13日14me-sa

(将 Dictionary 转换为 ILookup 不是很好: How do I convert a Dictionary to a Lookup? )

我想使用以下方法为我的容器类提供一个接口(interface):

ILookup<Type, Entry> Query ( IEnumerable<QueryClause> query ); 

每个查询子句指定应从底层容器中取出哪些和多少(以及更多详细信息)特殊类型的条目。

我的实现目前看起来像这样:

var result = new Dictionary<Type, List<Entry>>(); 
 
foreach(var clause in query) 
{ 
    var clauseResult = FulfillClause(clause); 
    result.Add(clause.Type, clauseResult); 
} 
 
return result.ToLookup(); // here it is 

这个方法有可能直接返回 ILookup 吗?很遗憾,它不支持 yield return。

请您参考如下方法:

我不完全确定你为什么要有这本字典。这对你有用吗?

return query.ToLookup(clause => clause.Type, clause => FullFillClause(clause)); 

它不符合 ILookup<Type, Entry>界面,但您提供的代码也没有,所以我无法确定您真正想要什么。

这是重新阅读问题后的尝试:

return query.SelectMany(c => FulfillClause(c).Select(r => new {Type=c.Type, Result=r})) 
            .ToLookup(o => o.Type, o => o.Result); 

这是@JonSkeet 链接答案的翻译。

为了在不知道所有类型和方法的细节的情况下进行测试,我使用了这个:

Func<List<int>> f = () => new List<int>() {1, 2, 3}; 
var query = new List<Type> {typeof (int), typeof (string)}; 
 
var l = query.SelectMany(t => f().Select(n => new {Type = t, Result = n})) 
    .ToLookup(o => o.Type, o => o.Result); 

如果您控制所有代码,您可以重组其中的一些代码以增强可读性:

return query.SelectMany(c => c.Fulfill()) 
            .ToLookup(res => res.Type, res => res.Value); 
 
... 
// You will need to create the ClauseFulfillment type yourself 
public IEnumerable<ClauseFulfillment> FulFill() 
{ 
   var results = // whatever FulfillClause does 
   foreach(var r in results) 
      yield return new ClauseFulfillment {Type = Type, Result = r};  
}