linq group by并选择不在group by中的多个列 [英] linq group by and select multiple columns not in group by
问题描述
我正在尝试使用linq-c#选择不在组中的多个列.
I'm trying to select multiple columns not in a group by using linq - c#.
使用linq,我尝试按ISNULL(fieldOne,''),ISNULL(fieldTo,'')进行分组,然后为每个组选择field_One,field_Two,field_Three.因此,对于group by将返回的每一行,我想看到很多行.
Using linq, I'm trying to group by ISNULL(fieldOne,''),ISNULL(fieldTo,'') and then select field_One, field_Two, field_Three for each group. So for each row that the group by would return, I want to see numerous rows.
到目前为止,我有以下内容,但似乎无法选择所有需要的列.
So far I have the following, but can't seem to select all the needed columns.
var xy = tableQueryable.Where(
!string.IsNullOrEmpty(cust.field_One)
|| ! string.IsNullOrEmpty(ust.field_Two)
).GroupBy(cust=> new { field_One= cust.field_One ?? string.Empty, field_Tow = cust.field_Two ?? string.Empty}).Where(g=>g.Count()>1).AsQueryable();
有人可以帮忙吗?
推荐答案
您几乎在那里-所缺少的只是该组中的Select
:
You are pretty much there - all you are missing is a Select
from the group:
var xy = tableQueryable
.Where(!string.IsNullOrEmpty(cust.first_name) || ! string.IsNullOrEmpty(ust.lastName))
.GroupBy(cust=> new { first_name = cust.first_name ?? string.Empty, last_name = cust.last_name ?? string.Empty})
.Where(g=>g.Count()>1)
.ToList() // Try to work around the cross-apply issue
.SelectMany(g => g.Select(cust => new {
Id = cust.Id
, cust.FirstName
, cust.LastName
, cust.RepId
}));
每个组中的
Select
进行所需字段的投影,而SelectMany
将所有结果转储到平面列表中.
Select
from each group does the projection of the fields that you want, while SelectMany
dumps all the results into a flat list.
这篇关于linq group by并选择不在group by中的多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!