我有以下代码根据类型计算卡的外观:

// counters initialization
var counters = new Dictionary<int, int>();
for (int i = 2; i <= 14; i++)
  counters.Add(i, 0);

// loop through and count number of appearances
for (int i = 0; i < playerCards.Length; i++)
  counters[playerCards[i]]++;

// Eg output:
// playerCards = { 9, 9, 3, 3, 10 }
// counters = ( (2, 0) , (3, 2) , (4, 0) , (5, 0) , (6, 0) , (7, 0) ,
//              (8, 0) , (9, 2) , (10, 1), (11, 0), (12, 0), (13, 0), (14, 0) )


LINQ是否有解决方案?

最佳答案

效果很好:

var playerCards = new [] { 9, 9, 3, 3, 10 };

var lookup = playerCards.ToLookup(x => x);

var counters = Enumerable.Range(2, 13)
    .ToDictionary(x => x, x => lookup[x].Count());


我得到了这个结果:



如果您乐于放弃查找,那么这也将起作用:

var counters = Enumerable.Range(2, 13)
    .ToDictionary(x => x, x => playerCards.Count(y => y == x));

关于c# - 对于进入LINQ的循环...可能吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22436487/

10-13 07:51