基于键 C# 合并两个列表
我有班级奖励,我可以保留每场比赛的用户资金。 我有两个列表,我需要以某种方式连接起来。我在下面写了示例列表和期望的结果。
public class Reward
{
public int Game { get; set; }
public int User { get; set; }
public int Money { get; set; }
public Reward Merge(Reward p)
{
return new Reward { Game = this.Game, User = this.User, Money = this.Money + p.Money};
}
}
IList<Reward> list1 = new List<Reward>();
list1.Add(new Reward {Game = 1, User = 1, Money = 10});
list1.Add(new Reward { Game = 1, User = 2, Money = 20 });
list1.Add(new Reward { Game = 1, User = 3, Money = 30 });
IList<Reward> list2 = new List<Reward>();
list2.Add(new Reward { Game = 2, User = 1, Money = 15 });
list2.Add(new Reward { Game = 2, User = 2, Money = 25 });
list2.Add(new Reward { Game = 2, User = 4, Money = 35 });
结果列表应该是
User Money
1 25
2 45
3 30
4 35
我尝试的
IList<Reward> listConcat = list1.Concat(list2)
.GroupBy(u=> u.User)
.Select(???)
.ToList();
但如何?
I have class Reward which i keep user money per game.
I have two list somehow I need to concate. I write sample lists and desired result below.
public class Reward
{
public int Game { get; set; }
public int User { get; set; }
public int Money { get; set; }
public Reward Merge(Reward p)
{
return new Reward { Game = this.Game, User = this.User, Money = this.Money + p.Money};
}
}
IList<Reward> list1 = new List<Reward>();
list1.Add(new Reward {Game = 1, User = 1, Money = 10});
list1.Add(new Reward { Game = 1, User = 2, Money = 20 });
list1.Add(new Reward { Game = 1, User = 3, Money = 30 });
IList<Reward> list2 = new List<Reward>();
list2.Add(new Reward { Game = 2, User = 1, Money = 15 });
list2.Add(new Reward { Game = 2, User = 2, Money = 25 });
list2.Add(new Reward { Game = 2, User = 4, Money = 35 });
Result List should be
User Money
1 25
2 45
3 30
4 35
I try
IList<Reward> listConcat = list1.Concat(list2)
.GroupBy(u=> u.User)
.Select(???)
.ToList();
but how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您使用 GroupBy 的方式是正确的,这应该可以完成工作:
编辑:与 lambda 表达式相同:
You were on the right track with GroupBy, this should do the job:
EDIT: Same thing with lambda expression:
这不是很漂亮,但是很有效。
This isn't very pretty, but it works.
使用
.GroupBy
,您将获得IGrouping
列表,因此选择如下所示:With
.GroupBy
, you get a list ofIGrouping
, so the select is like so:我想象一个接近您正在寻找的答案看起来像这样:
至于要使用哪个游戏,您可能会考虑匿名选择(即
这将为您提供一个匿名类型,其中包含您希望使用的信息。如果您是要将其传递出该方法,但是,最佳实践是为其指定类型,或者仅了解游戏 0 是所有游戏的超集。
I imagine an answer close to what you are looking for looks like this:
As far as which game to use, you might consider an anonymous select (i.e.
This would give you an anonymous type that holds the information you wish to use. If you are going to pass it out of the method, however, it's best practice to give it a type, or just understand that game 0 is your superset of all games.
请将行更改
为:
Please change the line:
to