这个问题是我在这里提出的问题的延续: Group by column to count duplicated values from another column in LINQ WPF
感谢这里的人们的大力帮助,我能够获得以下输出
+--------+-------+---------+------+
| Name | Score | Average | Star |
+--------+-------+---------+------+
| John | 15 | 5 | 3 |
| Hannah | 13 | 4.3 | 1 |
| Lilly | 13 | 4.3 | 2 |
+--------+-------+---------+------+
所以我想知道是否可以获得以下输出
+--------+-------+---------+------+------+
| Name | Score | Average | Star |Letter|
+--------+-------+---------+------+------+
| John | 15 | 5 | 3 | A |
| Hannah | 13 | 4.3 | 1 | C |
| Lilly | 13 | 4.3 | 2 | B |
+--------+-------+---------+------+------+
基本上,对于3星,字母应为A,2,B和1,C。我认为这可以使用if语句轻松实现,但它没有用。
这是我的代码:
public string Name { get; private set; }
public int Score { get; set; }
public decimal Average { get; set; }
public decimal Count { get; set; }
public int Star { get; set; }
public Person(string name, int score, decimal avg, int count, int star)
{
Name = name;
Score = score;
Average = avg;
Count = count;
Star = star;
}
public ObservableCollection<Person> Persons { get; set; }
filepath = scoresFile;
public MainWindow()
{
InitializeComponent();
LoadTable();
}
private void datagrid_Sorting(object sender, DataGridSortingEventArgs e)
{
if (e.Column.Header.Equals("Name") || e.Column.Header.Equals("Score"))
{
e.Handled = true;
}
}
public void LoadTable()
{
var lines = File.ReadAllLines(filepath);
Persons = new ObservableCollection<Person>();
var data = lines.Select(line =>
{
var column = line.Split(',');
int c = column[1].Count();
var name = column[1];
int score = int.Parse(column[3]);
decimal avg = decimal.Parse(column[3]);
int count = 0;
int star = 0;
char letter;
return new { name, score, avg, count, star};
});
var groupedData = data.GroupBy(p => p.name)
.Select((g, i) => new {
num= 0, name = g.Key,
score = g.Sum(p => p.score),
avg = decimal.Round(g.Average(p => p.avg), 1),
star = g.Count(p => p.score == 5) })
.OrderByDescending(x => x.avg);
if (groupedData.Where(u => u.star == 3 ))
{
letter = "A"
}
else if (groupedData.Where(u => u.star == 2 ))
{
letter = "B"
}
else
{
letter = "C"
}
var persons = groupedData.Select((p, i) => new Person(i + 1, p.name, p.score, p.avg, p.count, p.star));
foreach (var person in persons)
{
Persons.Add(person);
}
datagrid.ItemsSource = Persons;
}
这是我添加的新行,它不能与我合作:
if (groupedData.Where(u => u.star == 3 ))
{
letter = "A"
}
else if (groupedData.Where(u => u.star == 3 ))
{
letter = "B"
}
else
{
letter = "C"
}
知道我做错了什么吗?也许我没有在if语句中正确调用LINQ查询?
答案 0 :(得分:1)
使用以下代码更新groupedData
LINQ语句:
var groupedData = data.GroupBy(p => p.name)
.Select((g, i) => new {
num = 0,
name = g.Key,
score = g.Sum(p => p.score),
avg = decimal.Round(g.Average(p => p.avg), 1),
star = g.Count(p => p.score == 5),
letter = g.Count(p => p.score == 5) == 3 ? "A" : (g.Count(p => p.score == 5) == 2 ? "B" : (g.Count(p => p.score == 5) == 1 ? "C" : ""))
})
.OrderByDescending(x => x.avg);