本文介绍了合并两个列表基于键C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类奖励,我保持用户的钱每场比赛。
我有两个列表不知何故,我需要concate。我写的样本名单及以下所需的结果。

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

我尝试

IList<Reward> listConcat = list1.Concat(list2)
                .GroupBy(u=> u.User)
                .Select(???)
                .ToList();



但如何?

but how?

推荐答案

您在正确的轨道与GROUPBY上,这应该做的工作:

You were on the right track with GroupBy, this should do the job:

IEnumerable<Reward> 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表达式同一件事情:

EDIT: Same thing with lambda expression:

IEnumerable<Reward> 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)
    });

这篇关于合并两个列表基于键C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-13 19:29