首页 > 解决方案 > 将重复数据与列表中的条件合并

问题描述

我有一份成员名单:

 List<Members> MyMembers= new List<Members>();

会员类:

public class Members
{
     public int IdKey;
     public string name;
     public string relationBegin;
     public string relationEnd;
     public bool isOriginal;
 }

我需要将重复的 IdKey 合并为一个。这可以使用类似的东西来完成:

MyMembers=MyMembers.GroupBy(x => x.IdKey )
      .Select(g => new Members{ IdKey = g.Key })
      .ToList();

这是乐趣开始的地方。

条件是,如果我们检测到重复的 IdKey 它需要保留 isOriginal=true 的那个(如果两者都是 isOriginal=false,我们将 isOriginal 保留为 false,但更新日期开始和结束,如下文所述)

此外,我们需要保留两个副本中最低的relationBegin 和最高的relationEnd,有时relationBegin 或relationEnd 可能为Null 或空。

示例:第 1 行:

示例:第 2 行:

结果将是:

标签: c#linq

解决方案


如果你的Member班级有DateTime而不是字符串日期时间会更好。

如果您需要它们的字符串,您可以拥有如下属性。

public class Members
{
    public int IdKey;
    public string name;
    public string relationBegin;
    public string relationEnd;
    public bool isOriginal;

    public DateTime RelationBeginDate
    {
        get { return DateTime.ParseExact(relationBegin, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture); }
    }
    public DateTime RelationEndDate
    {
        get { return DateTime.ParseExact(relationEnd, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture); }
    }

    public Members(int IdKey, string name, string relationBegin, string relationEnd, bool isOriginal)
    {
        //assign paramters to proper properties
    }
}

您想要的linq将如下所示。

    MyMembers = MyMembers.GroupBy(x => x.IdKey)
      .Select(g => new Members(
         g.Key, //Id will be same as you shown in question
         g.FirstOrDefault().name, //assuming name will be same in all
         g.Select(x => x.RelationBeginDate).Min().ToString("dd-MM-yyyy hh:mm:ss"), //Min begin date
         g.Select(x => x.RelationEndDate).Max().ToString("dd-MM-yyyy hh:mm:ss"),   //Max end date
         g.Any( x => x.isOriginal))).ToList();      //if isOriginal = true found

推荐阅读