2

假设我有以下对象的通用列表:

public class Supermarket
{
    public string Brand { get; set; }
    public string Suburb { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}

因此,使用一个List<Supermarket>填充了许多具有不同值的对象,我试图:

  1. 从 a 中包含的对象超集中选择不同的Suburb属性(例如,此超集包含 20 个不同的郊区)。SupermarketList<Supermarket>

  2. 将上面的 Distinct List of Suburbs 加入到另一组通过 LINQ 查询获得的聚合和计数的 Suburbs 到不同的、较小的List<Supermarket>

我的超集中不同的项目是:

"Blackheath"
"Ramsgate"
"Penrith"
"Vaucluse"
"Newtown"

我的聚合查询的结果是:

"Blackheath", 50
"Ramsgate", 30
"Penrith", 10

我想加入他们以获得

"Blackheath", 50
"Ramsgate", 30
"Penrith", 10
"Vaucluse", 0
"Newtown", 0

这是我到目前为止所尝试的:

var results = from distinctSuburb in AllSupermarkets.Select(x => x.Suburb).Distinct()
                select new
                {
                    Suburb = distinctSuburb,
                    Count = (from item in SomeSupermarkets
                            group item by item.Suburb into aggr
                            select new
                            {
                                Suburb = aggr.Key,
                                Count = aggr.Count()
                            } into merge
                            where distinctSuburb == merge.Suburb
                            select merge.Count).DefaultIfEmpty(0)
                } into final
                select final;

这是我第一次不得不在 Stack Overflow 上发帖,因为它是一个非常棒的资源,但我似乎无法为此拼凑出一个解决方案。

谢谢你的时间

编辑:好的所以我在最初的帖子后不久解决了这个问题。我唯一缺少的是在调用 to.ElementAtOrDefault(0)之后链接调用 to .DefaultIfEmpty(0)。我还验证了使用.First()而不是.DefaultIfEmpty(0)像 Ani 指出的那样有效,正确的查询如下:

var results = from distinctSuburb in AllSupermarkets.Select(x => x.Suburb).Distinct()
                select new
                {
                    Suburb = distinctSuburb,
                    Count = (from item in SomeSupermarkets
                            group item by item.Suburb into aggr
                            select new
                            {
                                Suburb = aggr.Key,
                                Count = aggr.Count()
                            } into merge
                            where distinctSuburb == merge.Suburb
                            select merge.Count).DefaultIfEmpty(0).ElementAtOrDefault(0)
                } into final
                select final;

最后:我运行了 Ani 的代码片段并确认它运行成功,因此这两种方法都有效并解决了原始问题。

4

1 回答 1

2

我不太了解StateSuburb( ) 之间假定的等效性,但您可以在调用后where distinctSuburb == merge.State添加 a 来修复您的查询。.First()DefaultIfEmpty(0)

但这是我将如何编写您的查询:使用GroupJoin

var results = from distinctSuburb in AllSupermarkets.Select(x => x.Suburb).Distinct()
              join item in SomeSupermarkets 
                        on distinctSuburb equals item.Suburb
                        into suburbGroup
              select new
              {
                    Suburb = distinctSuburb,
                    Count = suburbGroup.Count()
              };
于 2012-06-06T13:14:13.350 回答