问题描述
我一直在努力寻找一种方法,使LINQ能够选择给定列表的前n%个.我能够获得的最接近的是take语句,该语句的用法类似于TOP PERCENT SQL语句,但不支持百分比.我确定我缺少明显的东西,但似乎看不到.
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.
推荐答案
假设源是ICollection<T>
(而不仅仅是IEnumerable<T>
),则可以执行以下操作:
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);
}
请注意,它可以与IEnumerable<T>
一起使用(使用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.
这篇关于使用LINQ获得列表的前N个百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!