我有两个清单。一个是玩家的字符串列表,另一个是int列表,表示每个玩家的提及次数。 (对于玩家列表中的每个元素,提及列表中有一个元素)。在玩家列表中有重复的玩家,例如在NumofMentions列表中有3个玩家"玩家1"以及5,10,13个提及的数量。我想消除重复值但保留提及次数的总和。对于前面提到的例子,我想要一个" player1"提及的数量为28。
最简单的方法是什么?
答案 0 :(得分:1)
不要使用List;使用字典
var mentions = new Dictionary<string, int>();
mentions["PlayerName"] = 5;
var currentCount = mentions["PlayerName"];
mentions["PlayerName"] = currentCount + amountToAdd;
您仍然可以从Dictionary的Keys属性中获取所有玩家
foreach(var player in mentions.Keys)
{
//do some work
}
鉴于您有四个列表,请为每个列表执行以下操作:
foreach(var playerCounter in googleQueryList)
{
if(mentions.ContainsKey(playerCounter.Name))
{
//Update the player here
var currentCount = mentions[player.Name];
mentions[player.Name] = currentCount + playerCounter.NumOfMentions;
}
else
{
//Add the player here
mentions[player.Name] = playerCounter.NumOfMentions;
}
}
答案 1 :(得分:1)
听起来你的玩家名称和价值观是相辅相成的,也许他们不应该属于2个单独的列表,而是属于班级玩家的列表。您还没有向我们展示任何代码,因此我们必须使用我们自己对您的问题的解释,但这是我将如何处理它...
public class Player
{
public string name { get; set; }
public int value { get; set; }
}
public void MyTest()
{
var myList = new List<Player>
{
new Player { name = "Player 1", value = 5 },
new Player { name = "Player 1", value = 10 },
new Player { name = "Player 1", value = 13 },
new Player { name = "Player 2", value = 3 },
new Player { name = "Player 2", value = 4 },
new Player { name = "Player 2", value = 6 }
};
var mySummedList = myList.GroupBy(x => x.name).Select(x => new Player { name = x.Key, value = x.Sum(y => y.value)});
foreach(var val in mySummedList)
{
Debug.WriteLine(String.Format("{0}: {1}", val.name, val.value));
}
}
//Output:
//Player 1: 28
//Player 2: 13