【问题标题】:Using Linq to check if generic list in Dictionary contains a value使用 Linq 检查 Dictionary 中的泛型列表是否包含值
【发布时间】:2013-05-19 08:47:49
【问题描述】:

如何检查字典是否已经包含一组坐标?我正在使用 SelectManager 和 Where 但计数仍然错误。我认为它没有检查通用列表中的值。

我希望它遍历 matchTile 并检查通用列表中的所有其他元素是否存在条件(不是问题的一部分)。

如果满足该条件,它会将其添加到同一组中。当下一次迭代到来时,它应该检查该元素是否已经添加到组中。如果是,它会跳过它。如果没有,它会创建一个新组(列表)。

谁能帮忙?

private void groupMatches(List<int[]> matchTile){
    Dictionary<int, List<int[]>> groups = new Dictionary<int, List<int[]>>();
    int i = 0;

    foreach(int[] coord in matchTile){
        var alreadyCounted = groups.SelectMany(x => x.Value).Where(x => x[0] == coord[0] && x[1] == coord[1]);

        Debug.Log ("counted: " + alreadyCounted.Count ());

        if(alreadyCounted.Count() > 0) continue;

        // Create new group
        groups.Add(i, new List<int[]>());   
        groups[i].Add(coord);

        foreach(int[] nextCoord in matchTile){
            if (...)
            {
                groups[i].Add(nextCoord);   
            }
        }

        i++;
    }   

    Debug.Log ("groups: " + groups.Count);
}

【问题讨论】:

    标签: linq dictionary foreach generic-list


    【解决方案1】:

    尝试下一个代码:

    private void groupMatches(List<int[]> matchTile)
    {    
        Dictionary<int, List<int[]>> groups 
             = matchTile.GroupBy(line => new{x = line[0], y = line[1]})
                        .Select((grp, index) => new{index, grp})
                        .ToDictionary(info => info.index, info => info.grp.ToList());
    
        Debug.Log("groups: " + groups.Count);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 2016-06-02
      相关资源
      最近更新 更多