Linq to Objects-左外部将不同对象属性值连接到聚合计数
假设我有以下对象的通用列表:Linq to Objects-左外部将不同对象属性值连接到聚合计数,linq,left-join,distinct,aggregate-functions,Linq,Left Join,Distinct,Aggregate Functions,假设我有以下对象的通用列表: public class Supermarket { public string Brand { get; set; } public string Suburb { get; set; } public string State { get; set; } public string Country { get; set; } } 因此,使用一个列表,其中填充了许多具有不同值的对象,我试图: 从列表中选择不同的属性 列表中包含的超
public class Supermarket
{
public string Brand { get; set; }
public string Suburb { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
因此,使用一个列表
,其中填充了许多具有不同值的对象,我试图:
属性
列表中包含的超市
对象的超集(假设此超集包含20个
独特的郊区)
List
"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;
这是我第一次不得不发布堆栈溢出,因为它是一个非常好的资源,但我似乎无法拼凑出一个解决方案
谢谢你的时间
编辑:好的,我在第一篇文章发表后不久就解决了这个问题。我唯一缺少的是在调用.DefaultIfEmpty(0)
之后链接调用.ElementAtOrDefault(0)
。我还验证了使用.First()
而不是Ani指出的.DefaultIfEmpty(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).ElementAtOrDefault(0)
} into final
select final;
最后:我运行了Ani的代码片段,并确认它运行成功,因此这两种方法都有效并解决了原始问题。我真的不理解
状态和郊区(其中distinctSuburb==merge.State
)之间假定的等价性,但是您可以在DefaultIfEmpty(0)
调用之后添加.First()
来修复查询
但我将如何编写您的查询:使用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()
};
谢谢你,阿尼。我用我最初的方法解决了这个问题,并修复了您指出的我错误地混淆了州和郊区的房地产的问题。