开发者

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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜