本文介绍了如何直接返回ILookup(不使用Dictionary-> ILookup转换器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(将字典转换为 ILookup 不是很好:

(Converting a Dictionary to ILookup is not very nice:How do I convert a Dictionary to a Lookup? )

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

I want to have an interface for my container class with the following method:

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

每个查询子句指定一种特殊类型的条目应该有多少(和一些更多的细节)从基础容器中取出。

Each query clause specifies which and how many (and some more details) of a special kind of Entry should be taken out of the underlying container.

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

My implementation currently looks something like this:

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

Is there any chance this method my return ILookup directly? Unfortunately it does not support yield return.

推荐答案

我不是完全肯定你为什么你的字典在第一位。这是否适合你?

I'm not entirely sure why you have the dictionary in the first place. Does this work for you?

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

重新阅读这个问题后:

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

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

It's a translation of @JonSkeet's linked answer.

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

To test without knowing the details of all the types & methods, I used this:

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






如果你控制所有的代码,你可以重组一些提高可读性:


If you control all the code, you could restructure some of it to enhance readability:

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

这篇关于如何直接返回ILookup(不使用Dictionary-&gt; ILookup转换器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 20:38