C# Using Enumerable Range and Except with custom class to determine missing sequence number
I have a List<MyClass>
The class is like this:
private class MyClass
{
public string Name{ get; set; }
public int SequenceNumber { get; set; }
}
I want to work out what Sequence numbers might be missing. I 开发者_如何学运维can see how to do this here however because this is a class I am unsure what to do?
I think I can handle the except method ok with my own IComparer but the Range method I can't figure out because it only excepts int so this doesn't compile:
Enumerable.Range(0, 1000000).Except(chqList, MyEqualityComparer<MyClass>);
Here is the IComparer:
public class MyEqualityComparer<T> : IEqualityComparer<T> where T : MyClass
{
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
{
return (x == null && y == null) || (x != null && y != null && x.SequenceNumber.Equals(y.SequenceNumber));
}
/// </exception>
public int GetHashCode(T obj)
{
if (obj == null)
{
throw new ArgumentNullException("obj");
}
return obj.GetHashCode();
}
#endregion
}
You could always project the class to the sequence number, as that's what you're interested in from the class, which will give you an IEnumerable<int>
that can be directly excepted from the range, e.g.
Enumerable.Range(0, 1000000).Except(chqList.Select(c => c.SequenceNumber));
This will return the missing sequence numbers. Note that this assumes chqList
is a list of MyClass
objects.
精彩评论