How to check if a element is repeated in a IEnumerable?
This is a code example from solution. I'm looking for the way to eliminate Problem classes repeated. I was watching Contains method in List.
public IEnumerable<Problem> Create(int quantify)
{
for (i开发者_JAVA技巧nt i = 0; i < quantify; i++)
{
yield return Create();
}
}
If you simply want to eliminate any duplicates and Problem
supports equality then use the Distinct
method.
IEnumerable<Problem> collection = ...;
IEnumerable<Problem> noRepeats = collection.Distinct();
If you want to stick to an iterator block you could use an HashSet
to not yield any repeated Problem
instances in the first place:
public IEnumerable<Problem> Create(int quantify)
{
HashSet<Problem> problems = new HashSet<Problem>();
for (int i = 0; i < quantify; i++)
{
var problem = Create();
if(!problems.Contains(problem))
{
yield return problem;
problems.Add(problem);
}
}
}
If a distinction is based on the property you can use GroupBy
Create(q).GroupBy(p => p.PropertyToCompare).Select(p => p.First());
精彩评论