根据键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 list1 = new List(); 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 list2 = new List(); 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 listConcat = list1.Concat(list2) .GroupBy(u=> u.User) .Select(???) .ToList();
但是怎么样?
你在GroupBy的正确轨道上,这应该做的工作:
IEnumerable result = from r in list1.Concat(list2) group r by r.User into groupedRewards select new Reward { Game = 0, //what game to use? User = groupedRewards.Key, Money = groupedRewards.Sum(r => r.Money) };
编辑 :与lambda表达式相同:
IEnumerable result = list1.Concat(list2) .GroupBy(u => u.User) .Select(g => new Reward { Game = 0, //what game to use? User = g.Key, Money = g.Sum(r => r.Money) });
这不是很漂亮,但它确实有效。
var listConcat = list1.Concat(list2) .GroupBy(u=> u.User) .Select(rewards => new Reward { User = rewards.Key, Money = rewards.Select(reward => reward.Money).Sum() } ) .ToList();
使用.GroupBy
,您将获得一个IGrouping
列表,因此select就像这样:
IEnumerable listConcat = list1.Concat(list2) .GroupBy(x => x.User) .Select(x => new Reward { User= x.Key, Money=x.Sum(y => y.Money) });
我想一个接近你正在寻找的答案看起来像这样:
var catList = list1.Concat(list2) .GroupBy (x => x.User) .Select (y => new Reward{Game = 0, Money = y.Sum (z => z.Money), User = y.Key}) .ToList();
至于使用哪种游戏,您可以考虑匿名选择(即
.Select(new {Money = y.Sum (z => z.Money), User = y.Key})
这将为您提供一个匿名类型,其中包含您要使用的信息。 但是,如果要将其从方法中删除,最佳做法是给它一个类型,或者只是理解游戏0是你所有游戏的超集。
IList listConcat = list1.Concat(list2) .GroupBy(person => person.User) .Select(group => group.Aggregate((rewardone, rewardtwo) => rewardone.Merge(rewardtwo))) .ToList();
请更改行:
return new Reward { Game = this.Game, User = this.User, Money = this.Money + p.User
至
上述就是C#学习教程:根据键c#合并两个列表分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
return new Reward { Game = this.Game, User = this.User, Money = this.Money + p.Money
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1030993.html