现在有一个list范型student,这个list里有若干个studentModel,model有这些字段:姓名、年龄等等,我现在想对这个list进行循环分组:select 姓名、年龄 from list group by 姓名、年龄。怎么用linq写出来;如果更新list里的某些字段用linq怎么写。多谢各位
var query = list.GroupBy(x => new { x.姓名, x.年龄 });
foreach (var item in query)
{
Console.WriteLine("分组 - " + x.Key);
foreach (studentModel s in item)
{
Console.WriteLine("\t" + x.姓名 + ...);
}
Console.WriteLine();
}
修改直接找就可以
int x = list.FindIndex(x => 条件);
list[x].属性 = xxx
用年龄分组如下:
var query = from s in studentList
group s by s.Age
linq写法如下,lambda如caozhy写法.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>()
{
new Student() { 姓名="张三", 年龄=24 },
new Student() { 姓名="李四", 年龄=26 },
new Student() { 姓名="王五", 年龄=28 },
new Student() { 姓名="张三", 年龄=24 },
new Student() { 姓名="李四", 年龄=24 },
};
var result = from s in students
group s by new { s.姓名, s.年龄 } into g
select new
{
姓名 = g.Key.姓名,
年龄 = g.Key.年龄,
};
foreach (var r in result)
{
Console.WriteLine("姓名={0},年龄={1}", r.姓名, r.年龄);
}
}
}
public class Student
{
public string 姓名 { get; set; }
public int 年龄 { get; set; }
}
}