【问题标题】:Does linq to sql have a with ties option?linq to sql 是否有 with ties 选项?
【发布时间】:2009-08-27 18:15:37
【问题描述】:

我正在尝试将以下查询移至 Linq-to-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 中的关系有关。

【问题讨论】:

    标签: linq-to-sql


    【解决方案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 的逻辑。

    【讨论】:

    • 非常好。虽然我希望它是 IOrderedQueryable 的扩展。
    • 天哪。我不知道 IOrderedQueryable。我已经更新了代码。
    • 这看起来不会产生像 T-SQL TOP n PERCENT WITH TIES 这样的结果。考虑数据1 2 2 3 3 3 4 4 4 4 ... 100,它有5050 个条目。 TOP 1 PERCENT WITH TIES 将返回 55 行(直到值 10),而您的函数仅返回 1 行。
    • 没有投反对票,但这个答案不像WITH TIES那样工作。正如 Ben Voigt 所说,如果您考虑由 {3 2 2 1 1 0} 组成的数据集,则结果集将是 {3 2 2 1 1}(与关系行为一样)应该是 {3 2 2}
    猜你喜欢
    • 2014-04-05
    • 1970-01-01
    • 2010-12-31
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多