使用C#我想基于一个公共属性组合列表中的项目。例如:
class Merchant
{
public string Name { get; set; }
public string Value1 { get; set; }
public string Value2 { get; set; }
public DateTime? Value3 {get; set; }
}
列表包含:
{Name = "1", Value1 = "1", Value2 = "", Value3 = someDatetime}
{Name = "1", Value1 = "", Value2 = "2", Value3 = someDatetime}
{Name = "1", Value1 = "3", Value2 = "", Value3 = someDatetime}
{Name = "1", Value1 = "", Value2 = "4", Value3 = someDatetime}
{Name = "2", Value1 = "5", Value2 = "", Value3 = someOtherDatetime}
注意:空字符串值也可以为null
必需的输出列表:
{Name = "1", Value1 = "1,3", Value2 = "2,4", Value3 = someDateTime}
{Name = "2", Value1 = "5", Value2 = "", Value3 = someOtherDatetime}
这可以通过任何单个linq查询来实现吗?
更新:我添加了DateTime类型的新值。对于每个名称,只有一个日期时间(可以为null)。我如何在查询中包含它?
答案 0 :(得分:6)
var query = list.GroupBy(m => m.Name)
.Select(g => new Merchant
{
Name = g.Key,
Value1 = String.Join(",", g
.Where(m => !String.IsNullOrEmpty(m.Value1))
.Select(m => m.Value1)),
Value2 = String.Join(",", g
.Where(m => !String.IsNullOrEmpty(m.Value2))
.Select(m => m.Value2)),
Value3 = g.First().Value3
});
已更新 以考虑新的DateTime?
列。