如何检查IEnumerable是否有两个或多个具有相同属性值的项?
例如一个班级
public class Item
{
public int Prop1 {get;set;}
public string Prop2 {get;set;}
}
然后是IEnumerable<Item>
类型的集合
如果Prop1中有重复值的项,我需要返回false。
我认为这种方法会起作用。
public static bool ContainsDuplicates<T1>(this IEnumerable<T1> source, Func<T1, T2> selector)
{
var d = new HashSet<T2>();
foreach(var t in source)
{
if(!d.Add(selector(t)))
{
return true;
}
}
return false;
}
您想只检查Prop1吗?
关于什么:
IEnumerable<Item> items = ...
var noDistinct = items.GroupBy(x => x.Prop1).All(x => x.Count() == 1);
// it returns true if all items have different Prop1, false otherwise
一个简短的,只列举一个枚举的解决方案是:
public static bool ContainsDuplicates<T>(this IEnumerable<T> list)
=> !list.All(new HashSet<T>().Add);
这可以解读为:当All
项目可以被Add
-ed到一个集合时,列表没有重复。
这在概念上类似于Jake Pearsons解决方案;然而,它忽略了投影的独立概念; OP的问题将解决为:
items.Select(o => o.Prop1).ContainsDuplicates()
bool x = list.Distinct().SequenceEqual(list);
如果x
有重复,true
是list
。
您可以从IEnumerable中选择不同的值,然后根据完整集合的计数检查计数。
例:
var distinctItemCount = myEnumerable.Select(m => m.Prop1).Distinct().Count();
if(distinctItemCount < myEnumerable.Count())
{
return false;
}
这可能是针对性能的,但到目前为止它是唯一正确的答案。
// Create an enumeration of the distinct values of Prop1
var propertyCollection = objectCollection.Select(o => o.Prop1).Distinct();
// If the property collection has the same number of entries as the object
// collection, then all properties are distinct. Otherwise there are some
// duplicates.
return propertyCollection.Count() == objectCollection.Count();
public static class EnumerableEx
{
public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> source)
{
return source.GroupBy(t => t).Where(x => x.Count() > 1).Select(x => x.Key);
}
}
就个人而言,我喜欢扩展方法的整洁。如果您的对象不需要选择器来确定相等性,那么这很好用。
我们可以在.Distinct()
中使用ArrayList
删除重复的条目。
我在createdby
有一个testtable
列,有5个重复的条目。我必须只获得一排
ID Createdby
=== ========
1 Reddy
2 Reddy
3 Reddy
4 Reddy
考虑到上表,我只需要选择一个“Reddy”
DataTable table=new DataTable("MyTable");//Actually I am getting this table data from database
DataColumn col=new DataColumn("Createdby");
var childrows = table.AsEnumerable().Select( row => row.Field<object>(col)).Distinct().ToArray();