【问题标题】:Merging two IQueryables into a Dictionary with LINQ使用 LINQ 将两个 IQueryable 合并到字典中
【发布时间】:2016-06-29 22:52:57
【问题描述】:

我有一个 IQueryable 并希望将其填充到一个以 Foo 为键的字典中,并将该 Foo 的 Bars 集合的计数作为值。

public class Foo
{
    public string ID { get; set; }
    public ICollection<Bar> Bars { get; set; }
}

所以输出看起来像这样:

new Dictionary<Foo, int>
{
    { someFoo, 2 },
    { anotherFoo, 6 },
    ...
}

我需要直接从 IQueryable 中执行此操作,无需迭代实际对象。明确地说,我确实不想这样做:

// given some IQueryable<Foo> called 'foos' and some Dictionary<Foo, int> called 'dictionary'
foreach (var foo in foos.ToList())
{
    dictionary.Add(foo, foo.Bars.Count());
}

我尝试过的方法不起作用

方法一

var dictionary = foos.ToDictionary(key => key, value => foos.Select(foo => foo.Bars.Count));

方法2

var counts = foos.Select(foo => foo.Bars.Count);

for (var i = 0; i < foos.Count(); i++)
{
      dictionary.Add(foos.ElementAt(i), counts.ElementAt(i));
}

【问题讨论】:

  • 如果要获取集合的计数,没有办法避免枚举枚举。
  • 我不清楚你的限制。 “不迭代实际对象”是什么意思? ToDictionary 迭代 - 没有迭代就无法构建字典,它不是像 IQueryable 这样的惰性求值对象。

标签: c# linq iqueryable


【解决方案1】:

我很确定这会奏效,你试过了吗:

var dictionary = foos.ToDictionary(foo => foo, foo => foo.Bars.Count());

【讨论】:

    【解决方案2】:

    啊,这最终奏效了:

    var result = from foo in foos
                 select new
                 {
                     Foo = foo,
                     Count = foo.Bars.Count()
                 };
    

    该方法还有一个额外的好处是可以让我指定字段的名称,这在我将此对象序列化为 JSON 时非常有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 2012-04-19
      • 1970-01-01
      • 2021-04-10
      • 1970-01-01
      • 2018-05-13
      • 2015-11-15
      • 1970-01-01
      相关资源
      最近更新 更多