具有重复项的列表中的计算
我有一个类似的类
public class user
{
public int ID { get; set; }
public int money { get; set; }
}
和类似的数据
List<user> users = new List<user>();
user u1 = new user();
u1.ID = 1;
u1.money = 20;
users.Add(u1);
user u2 = new user();
u2.ID = 1;
u2.money = 30;
users.Add(u2);
user u3 = new user();
u3.ID = 2;
u3.money = 100;
users.Add(u3);
user u4 = new user();
u4.ID = 2;
u4.money = 200;
users.Add(u4);
user u5 = new user();
u5.ID = 3;
u5.money = 500;
users.Add(u5);
现在我想要一个用户列表,其中应该包含3个基于唯一ID的用户,并且他们的钱应该是根据重复的平均值。
任何提示都会很好。方向。
谢谢
i have a Class like
public class user
{
public int ID { get; set; }
public int money { get; set; }
}
and Data Like
List<user> users = new List<user>();
user u1 = new user();
u1.ID = 1;
u1.money = 20;
users.Add(u1);
user u2 = new user();
u2.ID = 1;
u2.money = 30;
users.Add(u2);
user u3 = new user();
u3.ID = 2;
u3.money = 100;
users.Add(u3);
user u4 = new user();
u4.ID = 2;
u4.money = 200;
users.Add(u4);
user u5 = new user();
u5.ID = 3;
u5.money = 500;
users.Add(u5);
Now i want a list of users which should contains 3 users based on Unique ID and and their Money should be the average according to repetition .
Any hint would be great in right direction.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我理解正确的话,这应该会给你你想要的 - 按
ID
对用户进行分组,然后计算money
的平均值:If I understand you correctly, this should give you what you want - group the users by
ID
and then calculate the average ofmoney
:使用 Linq 会很容易,请尝试:
Use Linq will be easy, please try:
如果您不能或不想使用 Linq,这里有另一个解决方案。另外,看起来您想要一个加权平均值,而其他发帖者似乎没有注意到。
向用户类添加一个初始值为 1 的 Weight 字段。创建一个字典,其中用户 ID 作为键,用户对象作为值。迭代您的“用户”列表并:
* 检查字典是否已经包含当前用户
* 如果没有,添加用户:dict.Add(user.ID, user)
* 如果是,则将该用户的权重增加 1: dict[user.ID].weight++
之后,您可以很容易地计算加权平均值。迭代 dict.Values,并在每次迭代中将 user.money*user.weight 添加到 sum 变量。在 foreach 循环之后,将其除以唯一用户的数量:
不要忘记将其中一个操作数转换为 double,否则这将被解释为整数除法(余数将被忽略)。
抱歉,示例不完整且格式不正确,但我是在手机上写的。
If you can't or don't want to use Linq, here's another solution. Also, it looks like you want a weighted average which the other posters seem not to have noticed.
Add a Weight field to the user class with an initial value of 1. Create a dictionary with the user ID's as keys and the user objects as values. Iterate over your 'users' list and:
* check if the dictionary already contains the current user
* if it doesn't, add the user: dict.Add(user.ID, user)
* if it does, increase the weight of that user by 1: dict[user.ID].weight++
After that you can calculate the weighted average pretty easily. Iterate over dict.Values, and add user.money*user.weight to a sum variable in each iteration. After the foreach loop, divide that by the number of unique users:
Don't forget to cast one of the operands to double because otherwise this will be interpreted as an integer division (the remainder will be ignored).
Sorry for the incomplete example and poor formatting but I'm writing this on my phone.