在嵌套列表中搜索最大值和索引

本文关键字:最大值 索引 搜索 嵌套 列表 | 更新日期: 2023-09-27 18:30:07

我知道我可以通过这种方式从一个简单的列表中获得最大值和索引

List<Employee> emplist = new List<Employee>()
                        {
                         new Employee{Age=15, name = "Tom"},
                         new Employee{Age=17, name = "Billy"},
                         new Employee{Age=25, name = "Sam"}
                        };
int maxvalue = emplist.Select(i => i.Age).Max();
int index = empList.FindIndex(t => t.Age == maxvalue);

但对于嵌套列表

List<Employee> emplist = new List<Employee>()
                    {
                     new Employee{Age=15, name = "Tom", new List<project>
                     {
                        ID = 12, name = "Project A",
                        ID = 11, name = "Project B",
                        ID = 16, name = "Project C"
                     }},
                     new Employee{Age=17, name = "Billy",new List<project>
                     {
                        ID = 17, name = "Project D",
                        ID = 18, name = "Project E",
                        ID = 10, name = "Project F"
                     }},
                     new Employee{Age=25, name = "Sam",new List<project>
                     {
                        ID = 22, name = "Project X",
                        ID = 24, name = "Project Y",
                        ID = 19, name = "Project Z"
                     }}
                    };

我知道如何获得ID的最大值,但不知道如何获得它的两个索引。

int maxvalue = emplist.SelectMany(i => i.project).Select(a => a.ID).Max();

最大值为24。我也想得到两个索引(员工的索引2和项目的索引1)

在嵌套列表中搜索最大值和索引

尝试以下Linq

var result =  emplist.Select((x,i) => new { index = i, item = x})
                     .SelectMany(x => x.item.project.Select(
                          (a,i) => new { index = x.index, subindex = i, id = a.ID}))
                     .OrderByDescending(x => x.id )
                     .First();
  • 第一个索引将在result.index=2中
  • 第二个索引将在result.subindex=1中
  • ID将处于result.id=24

您可以使用Select的重载来创建匿名类型:

var maxItem = emplist
   .Select((emp, index) => new 
    { 
        maxProject = emp.project
            .Select((proj, pIndex) => new{ proj, pIndex })
            .OrderByDescending(x => x.proj.ID)
            .First(),
        emp, index 
    })
    .OrderByDescending(x => x.maxProject.proj.ID)
    .First();
Console.Write("Max-Value:{0} Emp-Index:{1} Project-Index:{2}"
    , maxItem.maxProject.proj.ID
    , maxItem.index 
    , maxItem.maxProject.pIndex);

(免责声明:未经测试,假设所有员工都有一个非空的List<Employee> project

这将在不调整项目列表的情况下执行相同的操作:

    var employee    = emplist.Aggregate((e1, e2) => (e1.project.Max(p1 => p1.ID) > e2.project.Max(p2 => p2.ID)) ? e1 : e2);
    var employeeidx = emplist.IndexOf(employee);
    var project     = employee.project.Aggregate((p1, p2) => (p1.ID > p2.ID) ? p1 : p2);
    var projectidx  = employee.project.IndexOf(project);
    var value       = project.ID;