我的简化数据结构如下::
FieldA FieldB
abc
abc
abc emailabc
abc emailabc
def
def
def
ijk
ijk emailijk
abc emailabc1
abc emailabc1
我需要的输出::
FieldA FieldB
abc emailabc
def
ijk emailijk
abc emailabc1
我如何得到这个结果.. 我尝试做了一个groupby,但是在没有feildB的情况下也给出了重复的fieldA。
真心感谢任何帮助。
答案 0 :(得分:2)
这个LINQ查询应该处理它,即使有多个条目具有非空FieldB:
var result =
from item in items
group item by item.FieldA into grp
let nonEmpty =
from g in grp
where !String.IsNullOrEmpty(g.FieldB)
select g
from subItem in nonEmpty.Any() ? nonEmpty : grp
group subItem by new { subItem. FieldA, subItem.FieldB } into subGrp
select subGrp.First();
答案 1 :(得分:1)
您可以使用
var list = YourModel.GroupBy(x =>x.FieldA)
.Select(x => new
{
FieldA = x.Key,
FieldB = x.Max(y=>y.FieldB)
}).ToList();
有两列
var list = YourModel.GroupBy(x =>x.FieldA)
.Select(x => new
{
FieldA = x.Key,
FieldB = x.Max(y=>y.FieldB)
}).GroupBy(x => new { x.FieldA, x.FieldB })
.Select(x => new
{
FieldA = x.Key.FieldA,
FieldB = x.Key.FieldB
}).ToList();