List中有两个一样的元素,想把两个都去除,用remove和removeall都不行,list中是对象,distinct好像也不太好使,还请各位帮忙解答一下。 代码片段如下: class Edge { public PointF start; public PointF end; }
private List<Edge> edges = new List<Edge>();
经过计算后edges中有一些edge对象,有些对象是相同的线段,但是首尾可能相反,如何判断是相同的线段,并且将两个相同的都删除?
下面这种试下
List<User> nonDuplicateList1 = users.Distinct().ToList();//通过User类的Equals实现去重
class User:IEquatable<User>//继承IEquatable接口,实现Equals方法。List就可以使用Distinct去重 { public string name { get; set; } string address;
public User(string _name, string _address) { name = _name; address = _address; }
public override string ToString() { return string.Format(“name:{0},\taddress:{1}”, name, address); }
public bool Equals(User other) { return this.name == other.name; } public override int GetHashCode() { return name.GetHashCode(); } } 1.用GroupBy分组取第一条,实现去重,edges = edges.GroupBy(****).Select(x => x.First()).ToLust() 2.括号里是分组条件,这是一个对象分组new { a = x.start, b = x.end },用三元表达式解决你说的头尾小蜜蜂论坛回帖机倒装的情形
/// <summary> /// 可枚举类型扩展; /// </summary> public static class EnumerableExtensions { /// <summary> /// 按指定字段排除重复项; /// https://www.cnblogs.com/niuzaihenmang/p/5620915.html /// 示例:peopleList.DistinctBy(i => new { i.UserName }).ToList(); /// </summary> /// <typeparam name=”TSource”></typeparam> /// <typeparam name=”Tkey”></typeparam> /// <param name=”source”></param> /// <param name=”keySelector”></param> /// <returns></returns> public static IEnumerable<TSource> DistinctBy<TSource, Tkey>(this IEnumerable<TSource> source, Func<TSource, Tkey> keySelector) { HashSet<Tkey> hashSet = new HashSet<Tkey>(); foreach (TSource item in source) { if (hashSet.Add(keySelector(item))) { yield return item; } } } }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/231307.html原文链接:https://javaforall.cn