如何动态编辑对象列表cq#

时间:2016-09-12 14:56:08

标签: linq

    List<Scorer> hScorers;

    private void button_Click(object sender, RoutedEventArgs e)
    {

        hScorers = new List<Scorer>();
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "2'"});
        hScorers.Add(new Scorer() { PlayerRef = "moe", Time = "2'" });
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "5'" });
        hScorers.Add(new Scorer() { PlayerRef = "roe", Time = "2'" });
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "8'" });
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "3'" });

        int count = 0;
        foreach (var v in hScorers)
        {
                if (v.PlayerRef == hScorers[0].PlayerRef)
                {
                    if (count != 0)
                    {
                        hScorers[0].Time = hScorers[0].Time + ", " + v.Time;
                        v.PlayerRef = "";
                        v.Time = "";
                    }                     
                }
            count++;
        }
        hScorers.Where(x => x.PlayerRef == "")
            .ToList()
            .ForEach(x =>
            {
                if (x.PlayerRef == "")
                {
                    hScorers.Remove(x);
                }
            });            
        foreach (var scorer in hScorers)
        {
            listBox.Items.Add(scorer.PlayerRef + " "+ scorer.Time);
        }
    }

我想要实现的目标是有四个玩家有“乔”的参考,所以在对象列表中我想让一个玩家的玩家参数为“乔”,所以如果玩家存在格式将是

playerref =“joe”时间= 2',3',5',8'

或者如果一个玩家: playerref =“moe”时间= 2'

这段代码做了我想做的事,但它不是动态的。因为我使用hScorers [0] .PlayerRef对其进行了硬编码。而不仅仅是hScorers [0] .PlayerRef我希望它可以过滤所有可能的玩家。因此,如果它使用的列表中有5个玩家(编辑列表;简而言之,我想删除重复的玩家并将时间添加到现有实例):

hScorers[0].PlayerRef
hScorers[1].PlayerRef
hScorers[2].PlayerRef
hScorers[3].PlayerRef
hScorers[4].PlayerRef

1 个答案:

答案 0 :(得分:0)

使用Linq的GroupBy。以下应该做的工作:

hScorers = hScorers
    .GroupBy(s => s.PlayerRef)
    .Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
    .ToList();