如何在LINQ中获得具有最大价值的孩子? [英] How do I get child with maximum value in LINQ?

查看:91
本文介绍了如何在LINQ中获得具有最大价值的孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我正在使用Entity Framework,我有以下代码:



Hi all,

I am using Entity Framework and I have the following code:

var query = this._dbContext.Set<Parent>()
                .AsNoTracking()
                .Where(p => p.IsActive.Value)
                .Include(child=> p.Children)
                as IQueryable<Parent>;





这会给我所有的孩子。此外,孩子们有一个名为VersionNumber的属性。我应该如何编辑上面的查询,因为它只返回一个子项,即最大值为VersionNumber的子项。



请注意VersionNumber是一个INT递增的1,每个父母的每个孩子的记录。

父母子女.VersionNumber

1 1 1

1 2 2
2 1 1

2 1 2



非常感谢您的帮助



我尝试了什么:



我尝试了各种各样的事情,比如使用load方法。我还注意到Include子句不能在where里面



This would give me all the children. Also, children have a property named VersionNumber. How should I edit the query above so as it returns only one child, which is the one with the Max Value of VersionNumber.

Pls note VersionNumber is an INT incremented by 1, for each record of a child for each Parent.
Parent Child Child.VersionNumber
1 1 1
1 2 2
2 1 1
2 1 2

Many thanks for your help

What I have tried:

I've tried various things such as using the load method. I also noticed that the Include clause cannot have a where inside

推荐答案

你需要生成一个键来对结果进行排序,以找到最大的[max]值。类似于:

You need to generate a key to order the results by to find the largest [max] value. Something like:
var query1 = new List<List<int>>
{
    new List<int> { 1,1,1},
    new List<int> { 1,2,2},
    new List<int> { 1,1,1},
    new List<int> { 2,1,1},
    new List<int> { 2,1,2}
};

var query2 = query1.GroupBy(x => string.Join("", x))
                   .OrderByDescending(x => x.Key)
                   .First();



但你还需要对未对齐的数字进行面向未来,结果如下:


But you need to also 'future-proof' against unaligned numbers resulting in something like this:

var query2 = query1.GroupBy(x => string.Join("", x.Select(y => y.ToString().PadLeft(4, '0'))))
                   .OrderByDescending(x => x.Key)
                   .First();


这篇关于如何在LINQ中获得具有最大价值的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆