Selecting columns with linq with a nested dictionary

How do I get all the "columns" using linq from this dictionary.

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

where can i access the string this way

var someRow = _cells[2];

and i can get the cell

string cell = _cells[2][2];

What I'm trying to do is create a table.

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

Where do I get the values ​​of column A.

+3
source share
6 answers

Maybe this is what you are looking for?

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

This will go through the rows (internal dictionary) and just pull out the values ​​for the desired column.

+5
source

I suppose the "column" you are looking for is a string typed value in a nested dictionary?

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];
}
+1
source

, , . :

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

, 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();
0

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

, ,

0

To get column values ​​for all rows

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;
0
source

Source: https://habr.com/ru/post/1738897/


All Articles