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

时间:2013-09-04 14:37:55

标签: c#

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

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)

3 个答案:

答案 0 :(得分:3)

尝试以下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

答案 1 :(得分:2)

您可以使用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

答案 2 :(得分:1)

如果没有对您的项目列表进行处理,这将是相同的:

    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;