代码之家  ›  专栏  ›  技术社区  ›  Daniel A. White

使用linq和嵌套字典选择列

  •  3
  • Daniel A. White  · 技术社区  · 16 年前

    如何使用linq从这个字典中获取所有的“列”。

    Dictionary<int, Dictionary<int, string>> _cells;
    

    在这里我可以通过这条路进入一排

    var someRow = _cells[2];
    

    我能得到一个手机

    string cell = _cells[2][2];
    

    我想做的是创建表。

        A | B | C | ...
    1 | * | * | * | ... 
    2 | * | * | * | ... 
    3 | * | * | * | ... 
    

    在这里我得到A列的值。

    6 回复  |  直到 7 年前
        1
  •  5
  •   juharr    7 年前

    也许这就是你要找的?

    Dictionary<int, Dictionary<int, string>> _cells;
    int desiredColumn = 2;
    var col = _cells.Values.Select(d => d[desiredColumn]);
    

    它将遍历行(内部字典)并简单地拉出所需列的值。

        2
  •  1
  •   James Kolpack    16 年前

    我认为您要查找的“column”是嵌套字典中的字符串类型值?

    IEnumerable<string> GetColumnValues(
       Dictionary<int, Dictionary<int, string>> rows, int columnIndex)
    {
      return 
        from r in rows // key-value pairs of int->Dictionary<int,string>
        select r.Value[columnIndex];
    }
    
        3
  •  1
  •   Aaronaught    16 年前

    我想我明白你的要求了。要将此基于行的查找转换为基于列的查找:

    var columnLookup =
        (from row in _cells
         from col in row.Value
         let cell = new { Row = row.Key, Column = col.Key, Value = col.Value }
         group cell by cell.Column into g
         select new
         {
             Column = g.Key,
             Rows = g.ToDictionary(c => c.Row, c => c.Value)
         }).ToDictionary(c => c.Column, c => c.Rows);
    
        4
  •  0
  •   Anthony Pegram    16 年前

    你意识到这样做会丢失int键吗?

    Dictionary<int, string> dict1
        = new Dictionary<int, string>() { { 1, "Foo" }, { 2, "Blah" } };
    Dictionary<int, string> dict2 
        = new Dictionary<int, string>() { { 3, "Baz" }, { 4, "Ack" } };
    
    Dictionary<int, Dictionary<int, string>> collection 
        = new Dictionary<int, Dictionary<int, string>>() 
        { { 1, dict1 }, { 2, dict2 } };
    
    string[][] query = (from dict in collection
                 select dict.Value.Values.ToArray()).ToArray();
    
        5
  •  0
  •   vittore    16 年前

    试试这个

    Dic.Where(c=>c.Key==COLUMN).SelectMany(c=>c.Value).Where(f=>f.Key==FIELD)
    

    也许你可以先删除where语句

        6
  •  0
  •   Cornelius    16 年前

    获取所有行的列值

    int colIndex = 0;    // or whatever column you want
    var col =
            from a in cells
            from b in a.Value
            where b.Key == colIndex
            select b.Value;