выбрать все столбцы в сгруппированных данных linq - PullRequest
0 голосов
/ 25 мая 2018

Привет, у меня есть запрос linq. Я хочу отсортировать и суммировать все элементы на основе studentId, поэтому после некоторого поиска я нашел это:

 var res = _initialCollection.GroupBy(x => new { x.StudentId })
                        .Select(x => new
                        {
                            x.Key.StudentId,
                            Sum = x.Sum(y => AppVariable.EnumToNumber(y.Scores))
                        }).ToArray();

Теперь я хочу связать этот запрос с сеткой данных, но я не могу получить данные других столбцов,это моя таблица:

public long Id { get; set; }
            public long BaseId { get; set; }
            public long StudentId { get; set; }
            public string Name { get; set; }
            public string LName { get; set; }
            public string FName { get; set; }
            public string Scores { get; set; }

как я могу выбрать другие столбцы в этом запросе?ОБНОВЛЕНИЕ:

 var res = _initialCollection.GroupBy(x => new { x.StudentId })
                            .Select(x => new
                            {
                                x.Key.StudentId,
                                Sum = x.Sum(y => AppVariable.EnumToNumber(y.Scores))
                            }).ToArray();

Ответы [ 2 ]

0 голосов
/ 26 мая 2018
var res = _initialCollection.GroupBy(x => new { x.StudentId })
                            .Select(x => new 
                            {
                              StudentId=  x.Key,
                              Sum = x.Sum(y => AppVariable.EnumToNumber(y.Scores))
                              x.First().FName
                            }).ToList();
0 голосов
/ 25 мая 2018

Мы могли бы использовать приведенную ниже программу для эффективного использования LINQ, обратите внимание, что мы использовали OrderBy для сортировки по возрастанию (используйте OrderByDescending для сортировки по убыванию).Надеюсь, это поможет.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Solutions
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>()
                                         {
                                             new Student(){BaseId = 100, FName = "A", Id = 1, LName = "Z", Name = "A Z", Scores = "90", StudentId = 1},
                                             new Student(){BaseId = 100, FName = "A", Id = 2, LName = "Z", Name = "A Z", Scores = "10", StudentId = 1},
                                             new Student(){BaseId = 100, FName = "A", Id = 3, LName = "Z", Name = "A Z", Scores = "10", StudentId = 1},
                                             new Student(){BaseId = 100, FName = "B", Id = 2, LName = "Y", Name = "B Y", Scores = "91", StudentId = 2},
                                             new Student(){BaseId = 100, FName = "C", Id = 3, LName = "X", Name = "C X", Scores = "92", StudentId = 3},
                                             new Student(){BaseId = 100, FName = "D", Id = 4, LName = "W", Name = "D W", Scores = "93", StudentId = 4},
                                             new Student(){BaseId = 100, FName = "E", Id = 5, LName = "V", Name = "E V", Scores = "91", StudentId = 5},
                                         };

            // Total Score Select and Order By in the end for sorting
            var totalScoresSelect = students.GroupBy(student => student.StudentId).Select(
                groupedStudent => new
                {
                    StudentId = groupedStudent.Key,
                    TotalScore = groupedStudent.Sum(student => long.Parse(student.Scores)),
                    groupedStudent.First().FName,
                    groupedStudent.First().LName,
                    groupedStudent.First().Name
                }).OrderBy(totalScore => totalScore.TotalScore);

            foreach (var totalScore in totalScoresSelect)
            {
                Console.WriteLine(totalScore.StudentId);
                Console.WriteLine(totalScore.FName);
                Console.WriteLine(totalScore.LName);
                Console.WriteLine(totalScore.Name);
                Console.WriteLine(totalScore.TotalScore);
            }

            Console.ReadLine();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...