我很难找到合适的Linq查询来利用组输出。
我想填充一个现有的学生列表,其中Student类有2个属性 ID 和int [] Repeats 数组(可以是还要列出他们参加4次讲座中的任何一次(L101,L201,L202,L203)的次数。因此,如果学生两次使用L101,L202和L203一次,但是没有拿L201这应该是{2,0,1,1,}
class Student{
public string ID{get;set;}
public int[] Repeats{get;set;} //int[0]->L101, int[1]->L201...
}
在我的主课程中,我为此任务执行此基本操作:
foreach (var student in students)
{
var countL101 = from s in rawData
where student.Id==s.Id & s.Lecture =="L101"
select; //do for each lecture
student.Repeats = new int[4];
student.Repeats[0] = countL101.Count(); //do for each lecture
}
这有效;但我想知道如果有100多个讲座,你如何实际使用Linq?
答案 0 :(得分:0)
我使用 Lamba Expressions 而不是查询语法。然后假设rawData
为IEnumerable<T>
,其中T
看起来像......
class DataRow
{
/// <summary>
/// Id of Student taking lecture
/// </summary>
public string Id { get; set; }
public string Lecture { get; set;}
}
然后你可以做一些像......
var lectures = rawData.Select(x => x.Lecture).Distinct().ToList();
int i = 0;
lectures.ForEach(l =>
{
students.ForEach(s =>
{
if (s.Repeats == null)
s.Repeats = new int[lectures.Count];
s.Repeats[i] = rawData.Count(x => x.Id == s.Id && x.Lecture == l);
});
i++;
});
现在,如果Repeats
只能是IList<int>
类型而不是int[]
那么......
var lectures = rawData.Select(x => x.Lecture).Distinct().ToList();
lectures.ForEach(l =>
{
students.ForEach(s =>
{
if (s.Repeats == null)
s.Repeats = new List<int>();
s.Repeats.Add(rawData.Count(x => x.Id == s.Id && x.Lecture == l));
});
});
如果Repeats
只能在List<int>
构造函数中实例化为新的Student
,那么事情就会进一步简化......
class Student
{
public Student()
{
Repeats = new List<int>();
}
public string Id { get; set; }
public IList<int> Repeats { get; private set; }
}
然后你可以在一行中完成......
rawData.Select(x => x.Lecture).Distinct().ToList()
.ForEach(l =>
{
students.ForEach(s =>
{
s.Repeats.Add(rawData.Count(x => x.Id == s.Id && x.Lecture == l));
});
});