I have a custom subclass of BindingList<T> that I want to execute a LINQ query over using the handy extension methods. For example:
public int GetSum(MyList<T> list)
{
return list.Sum(x => x.Value);
}
But the compiler complains that it can't resolve Sum
because it doesn't recognize list
as an IEnumerable<T>
, which it obviously is, because this works:
public int GetSum(MyList<T> list)
{
return ((IEnumerable<T>)list).Sum(x => x.Value);
}
开发者_开发百科
Anyone have a clever way I can avoid the ugly and unecessary cast?
It would appear the compiler might be complaining about the type argument which the Sum
is attempting to be performed on since it can not be inferred. You can specify the type argument like this; where T is the type you want to perform the Sum
on.
return list.Sum<T>(x => x.Value);
It should be noted however that neither of your samples compiles for me even when reverting to the base BindingList<T>
without setting the type argument.
精彩评论