0

我很难找到合适的 Linq 查询来利用组输出。

我想填充一个现有的学生列表,其中学生类有 2 个属性ID和 int[]重复数组(也可以是一个列表)以保持他们参加 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?

4

1 回答 1

0

我使用的是Lamba 表达式而不是查询语法。然后假设看起来像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++;
});

现在 ifRepeats可能只是类型IList<int>而不是int[]then...

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>在构造函数中将其实例化为 new ,则事情会进一步简化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));
        });
    });
于 2013-09-07T16:57:10.663 回答