我覺得像這樣的東西會爲你工作。
public static IQueryable<T> TopPercentWithTies<T, TKey>(this IOrderedQueryable<T> query, Expression<Func<T, TKey>> groupByExpression, double percent)
{
var groupedQuery = query.GroupBy(groupByExpression);
int numberToTake = groupedQuery.Count() * percent/100;
return groupedQuery.Take(numberToTake).SelectMany(t => t);
}
我只用了IEnumerable測試它,所以我不知道肯定它會與IQueryable的正常工作。我還在調用TopPercentWithTies()之前對列表排序。
下面是我用來測試它的代碼。
int percent = 50;
var people = new []
{
new { Age = 99, Name = "Adam" },
new { Age = 99, Name = "Andrew" },
new { Age = 89, Name = "Bob" },
new { Age = 50, Name = "Cecil" },
new { Age = 50, Name = "Doug" },
new { Age = 50, Name = "Everett" },
new { Age = 35, Name = "Frank" },
new { Age = 25, Name = "Greg" },
new { Age = 15, Name = "Hank" }
};
var sortedPeople = people.AsQueryable().OrderByDescending(person => person.Age);
var results = sortedPeople.TopPercentWithTies(person => person.Age, percent);
foreach (var person in results)
Console.WriteLine(person);
希望它有助於或至少讓你在正確的方向。您可能需要調整計算numberToTake的邏輯。
非常好。儘管我希望它會是IOrderedQueryable的擴展。 – Maslow 2009-08-28 11:32:50
哦,甜美。我不知道IOrderedQueryable。我更新了代碼。 – Ecyrb 2009-08-28 16:44:46
這看起來不像它會產生像T-SQL'TOP n PERCENT WITH TIES'這樣的結果。考慮數據「1 2 2 3 3 3 4 4 4 4 ... 100」,其中有5050個條目。 'TIES'的TOP 1 PERCENT將返回55行(最大值爲10),而你的函數只返回1行。 – 2013-03-08 23:56:17