c# - 将重复数据与列表中的条件合并
问题描述
我有一份成员名单:
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 行:
- IsOriginal=true
- 关系开始 = 2017 年 1 月 1 日
- 关系结束 = 10/10/2018
示例:第 2 行:
- IsOriginal=false
- 关系开始 = 2015 年 1 月 1 日
- 关系结束 = NULL
结果将是:
- IsOriginal=真
- 关系开始=2015 年 1 月 1 日
- 关系End 10/10/2018
解决方案
如果你的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
推荐阅读
- android - 如何制作一个通用的 LiveData 类来处理 SharedPreferences?
- django - 带有 Django 的 Angular 路由器保护
- javascript - 同一地图上的多个选择交互不起作用
- c - 将库中定义的函数名作为 C 中的函数指针传递
- java - 当我单击like按钮时,它不会调用设置为调用的方法
- r - 如何在 R 的统计模型中识别使用的变量
- ios - 使用dylib创建ios框架
- unicode - 相同的 Unicode 字符有时显示为纯黑色,有时显示为彩色图标
- fluent-nhibernate - 流畅的休眠和自动映射器继承
- laravel - 未找到新组件