需要通过IdCordinator对记录进行分组, 条件
我应该如何构建我的where子句。如果我有一个如下的where子句,如果只有一个元素列表,虽然它不是“S”类,但它返回0条记录。
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqGroupbyWhere
{
class Program
{
static void Main( string[] args )
{
StudentList studentList = new StudentList();
studentList.getList();
Console.ReadKey();
}
}
public class StudentList
{
public void getList()
{
List<Students> stdLst = new List<Students>();
stdLst.Add( new Students( "stud1", 20, "M", "I001" ) );
stdLst.Add( new Students( "stud2", 20, "M", "I001" ) );
stdLst.Add( new Students( "stud3", 20, "M", "I002" ) );
stdLst.Add( new Students( "stud4", 20, "M", "I003" ) );
stdLst.Add( new Students( "stud5", 20, "S", "I001" ) );
stdLst.Add( new Students( "stud6", 20, "S", "I001" ) );
stdLst.Add( new Students( "stud7", 20, "S", "I002" ) );
var lst = stdLst.GroupBy( s => s.IdCordinator )
.SelectMany( sg =>
sg.Where( s => !s.Category.Equals( "S" ) || sg.Count( c => c.Category.Equals( "S" ) ) > 1 )
.Select( student => student.Name ) )
.OrderBy( o => o );
Console.WriteLine( string.Join( ",", (string[]) lst.ToArray() ) );
}
}
public class Students
{
public Students( string name, int age, string cat, string siCordinator )
{
this.Name = name;
this.Age = age;
this.Category = cat;
this.IdCordinator = siCordinator;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Category
{
get;
set;
}
public string IdCordinator
{
get;
set;
}
}
}
答案 0 :(得分:1)
你可以这样写它以获得你想要的输出:
var lst = stdLst.GroupBy(s => s.IdCordinator)
.SelectMany(sg =>
sg.Where(s => !s.Category.Equals("S") || sg.Count(c => c.Category.Equals("S")) > 1)
.Select(student => student.Name))
.OrderBy(o => o);
希望这能解决你的问题。
像这样更新你的构造函数:
public Students( string name, int age, string cat, string siCordinator )
{
this.Name = name;
this.Age = age;
this.Category = cat;
this.IdCordinator = siCordinator; // You were assiging same field to itself here, making it null
}