问题描述
我一直在尝试找到一种方法,让Linq能够选择给定列表的顶部N%.我获得的最接近的是拍摄声明,其作品与最高百分比SQL语句类似,但不支持百分比.我敢肯定我错过了一些明显的东西,但我似乎看不到它.
推荐答案
假设源是ICollection<T>(而不仅仅是IEnumerable<T>),您可以做这样的事情:
public static IEnumerable<T> TakePercent<T>(this ICollection<T> source, double percent) { int count = (int)(source.Count * percent / 100); return source.Take(count); }
请注意,它可以与IEnumerable<T>一起使用(使用Count()方法),但是它将列举两次序列,通常被认为是一件坏事.
问题描述
I have been trying to find a way for LINQ to be able to select the top n% of a given list. The closest I have been able to get is the take statement which works similarly to the TOP PERCENT SQL statement but doesn't support percentages. I'm sure I'm missing something obvious but I just can't quite seem to see it.
推荐答案
Assuming the source is an ICollection<T> (and not just an IEnumerable<T>), you can do something like that:
public static IEnumerable<T> TakePercent<T>(this ICollection<T> source, double percent) { int count = (int)(source.Count * percent / 100); return source.Take(count); }
Note that it could work with an IEnumerable<T> (using the Count() method), but it would enumerate the sequence twice, which is usually considered a bad thing.