public class DateDto
{
public int Id { get; set; }
public string BId { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
}
对这个类中的Cretetime进行排序,并且保留最新添加进来的值,首先要写一个自定义的类,排序类
public class PeopleAgeComparer : IComparer<DateDto>
{
public int Compare(DateDto dto,DateDto dto1)
{
TimeSpan sp = dto.CreateTime - dto1.CreateTime;
if (sp.Days > 0)
{
return -1;
} else if (sp.Days < 0)
{
return 1;
}
else
{
return 0;
}
}
}
去重类
public class Compare<T, C> : IEqualityComparer<T>
{
private Func<T, C> _getField;
public Compare(Func<T, C> getfield)
{
this._getField = getfield;
}
public bool Equals(T x, T y)
{
return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
}
}
public static class CommonHelper
{
/// <summary>
/// 自定义Distinct扩展方法
/// </summary>
/// <typeparam name="T">要去重的对象类</typeparam>
/// <typeparam name="C">自定义去重的字段类型</typeparam>
/// <param name="source">要去重的对象</param>
/// <param name="getfield">获取自定义去重字段的委托</param>
/// <returns></returns>
public static IEnumerable<T> MyDistinct<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
{
return source.Distinct(new Compare<T, C>(getfield));
}
}
操作
class Program
{
//第一步按照时间顺序排序
//第二步 去除重复得保留最新时间
static void Main(string[] args)
{
List<DateDto> dateDtos = new List<DateDto>();
DateDto dateDto1 = new DateDto()
{
Id = 1,
BId = "0001",
Name = "设备1",
CreateTime = DateTime.Parse("2020-9-27")
};
DateDto dateDto2 = new DateDto()
{
Id = 1,
BId = "0001",
Name = "设备1",
CreateTime = DateTime.Parse("2020-9-28")
};
dateDtos.Add(dateDto1);
dateDtos.Add(dateDto2);
//foreach (var item in dateDtos)
//{
// Console.WriteLine(item.CreateTime);
//}
// List<People> peoples = new List<People>()
// {
// new People() {age = 11, name="alun", sex = "男"},
// new People() {age=25, name = "陈敬桃", sex = "男"},
// new People() {age=9, name = "惠安", sex = "男"},
// new People() {age = 45, name = "小票", sex = "女"},
// new People() {age=3, name = "晓鸥", sex = "女"},
// new People() {age=70, name = "望谟", sex = "男"}
//};
dateDtos.Sort(new PeopleAgeComparer());
dateDtos = dateDtos.MyDistinct(c => c.Id).ToList();
foreach (var item in dateDtos)
{
Console.WriteLine(item.CreateTime);
}
Console.ReadKey();
}
}