我知道我可以用这种方式从一个简单的列表中获取最大值和索引
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)
答案 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 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;