tags:

views:

96

answers:

6

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

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

where I can access a row this way

var someRow = _cells[2];

and I am able to get a cell

string cell = _cells[2][2];

What I am trying to do is create table.

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

Where I get the values of column A.

+1  A: 

I take it that the "column" you're looking for is the string-typed value in the 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];
}
James Kolpack
From the original question, the problem is to select all of the columns (values, I assume). Rows are only mentioned with reference to how the data structure is organized.
James Kolpack
+1  A: 

I think I understand what you're asking for. You want to transform this row-based lookup into a column-based lookup:

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);
Aaronaught
A: 

You realize by doing this you are losing the int keys?

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();
Anthony Pegram
A: 

try this

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

maybe you can remove first where statement

vittore
+1  A: 

Maybe this is what you're looking for?

Dictionary<int, Dictionary<int, string>> _cells;
var cols = _cells.Select(p => p.Value)
                 .Where(d => d.Key == 2)
                 .SelectMany(d => d.Select(p => p.Value));
juharr
A: 

To get the 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;
Cornelius