嗨,我有一个这样的清单:
1 , Ali , 2017 , OK
2 , Ali , 2018 , OK
3 , Ali , 2017 , OK
4 , Ali , 2018 , Good
5 , Ali , 2017 , OK
6 , Ali , 2017 , Good
我希望根据日期加总重复项目,但首先我需要改变ok或good to int number somethings如下:
OK = 10
Good = 5
所以必须输出:
1 , Ali , 2017 , (10+10+10+5 = 35)
2 , Ali , 2018 , (10 + 5 = 15)
所以请帮助我!
答案 0 :(得分:4)
给定像
这样的实体class MyEntity
{
public int Id;
public string Name;
public int Year;
public string Valuation;
}
以及一些示例数据:
var coll = new[]
{
new MyEntity { Id = 1, Name = "Ali", Year = 2017, Valuation = "OK" },
new MyEntity { Id = 2, Name = "Ali", Year = 2018, Valuation = "OK" },
new MyEntity { Id = 3, Name = "Ali", Year = 2017, Valuation = "OK" },
new MyEntity { Id = 4, Name = "Ali", Year = 2018, Valuation = "Good" },
new MyEntity { Id = 5, Name = "Ali", Year = 2017, Valuation = "OK" },
new MyEntity { Id = 6, Name = "Ali", Year = 2017, Valuation = "Good" },
};
根据@arekzyla的建议,GroupBy
和Sum
的组合将提供所需的结果。
var grouped = coll.GroupBy(x => new { x.Name, x.Year })
.Select(x => new
{
x.Key.Name,
x.Key.Year,
Sum = x.Sum(y => y.Valuation == "OK" ? 10 : y.Valuation == "Good" ? 5 : 0)
}).ToArray();
注意:我不喜欢各种OK,Good ...如何转换为数字。您应该使用enum
和您要编写的特定方法EnumToNumber
来转换它们或类似的东西。类似的东西:
public static int EnumToNumber(string value)
{
switch (value)
{
case "OK":
return 10;
case "Good":
return 5;
default:
throw new ArgumentOutOfRangeException(nameof(value), value, "Value not recognized");
}
}
但请注意,我仍然在这里使用string
。总和将成为:
Sum = x.Sum(y => EnumToNumber(y.Valuation))
唯一感兴趣的是多字段分组(你没有要求它,但我把它放在代码中)。我按Name
和Year
分组(new { x.Name, x.Year }
是分组键)。
答案 1 :(得分:1)
import 'dart:async';
Future sleep1() {
return new Future.delayed(const Duration(seconds: 1), () => "1");
}
main() {
sleep1();
print('This will be logged to the console in the browser.');
}
假设您的课程 ID ,姓名,日期,状态