使用带有嵌套字典的linq选择列

时间:2010-03-28 23:27:02

标签: c# linq

如何使用此词典中的linq获取所有“列”。

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

我可以这样访问一行

var someRow = _cells[2];

我可以获得一个单元格

string cell = _cells[2][2];

我要做的是创建表格。

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

我在哪里得到A栏的值。

6 个答案:

答案 0 :(得分:5)

也许这就是你要找的东西?

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

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

答案 1 :(得分:1)

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

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];
}

答案 2 :(得分:1)

我想我理解你所要求的。您希望将此基于行的查找转换为基于列的查找:

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);

答案 3 :(得分:0)

你意识到这样做会丢失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();

答案 4 :(得分:0)

试试这个

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

也许你可以先删除where语句

答案 5 :(得分:0)

获取所有行的列值

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;