是否LINQ to SQL中有一个与领带的选择吗?(Does linq to sql have a

2019-07-03 21:42发布

我想下面的查询移动到LINQ到SQL,这可能吗?

select * from (
Select top (@Percent) percent with ties *
from(
    Select distinct
      LoanNumber as LoanNo
    From CHE 
    Left Join RecordingInfo as Rec
    On CHE.LoanNumber = Rec.LoanNo
    Where Channel = 'LINX'
        and CHE.Doc in ('MTG','MOD')
        and Rec.LoanNo is null
        and LoanNumber >= '@LoanNo'
) A
order by LoanNo @Order
) B
order by LoanNo

我还没有看到反正在LINQ的关系做。

Answer 1:

我觉得这样的事情会为你工作。

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。



文章来源: Does linq to sql have a with ties option?
标签: linq-to-sql