Return true or false based on whether there are duplicates
When I have duplicates in my collection, I want to return true, otherwise, I want to return false.
I've got the following linq query.
var开发者_运维技巧 t = from i in selectedDrivers
group i by i.Value into g
where g.Count() > 1
select g.Count() > 1;
Problem is though, that when there are multiple duplicates, it will return multiple trues, and if there aren't any duplicates, it returns nothing (should be false).
Problem is though, that when there are multiple duplicates, it will return multiple trues, and if there aren't any duplicates, it returns nothing (should be false).
Well that's easy to solve:
bool hasDupes = t.Any();
If there are multiple trues, that'll be true. If there are none, it'll be false.
But frankly, I would be inclined to simply write my own extension method that bails when it finds the first duplicate, rather than building up a set of all the duplicates and then querying that set:
static bool HasDuplicates<T>(this IEnumerable<T> sequence)
{
var set = new HashSet<T>();
foreach(T item in sequence)
{
if (set.Contains(item))
return true;
set.Add(item);
}
return false;
}
And now just say
bool dupes = selectedDrivers.HasDuplicates();
Easy peasy.
var t = (from i in selectedDrivers
group i by i.Value into g
where g.Count() > 1
select g.Count() > 1).Any();
I BELIEVE this will do the trick.
Aggregate your results in an or.
var q=from i in selectedDrivers
group i by i.Value into g
where g.Count() > 1
select g.Count() > 1
return q.Aggregate(false,(x,y)=>x|y);
Not the most optomised solution, but....
var t = selectedDrivers.Distinct().Count() != selectedDrivers.Count();
Here it is.
var t = selectedDrivers
.GroupBy(item => item.Value)
.Any(group => group.Skip(1).Any());
I have used 'group.Skip(1).Any()' to find a group with at least two elements and avoid enumerating the entire group with Count().
This isn't as good as Eric's solution, because it will group the entire enumeration, but this seems like the right way to use Any
here.
var t = selectedDrivers
.GroupBy(item => item.Value)
.Any(group => group.Count() > 1)
精彩评论