PawanS PawanS - 27 days ago 13
C# Question

LINQ dictionary to jagged array?

There is a method that returns 2D array, this method querying a dictionary from LINQ query and trying to store keys and values in 2D array.

But I am not able to do that

public string[][] GetRecordFields(string selectedRecord)
{

var recordFields = (from record in _recordMasterList
where record.Item1 == selectedRecord
select new
{
record.Item2.Keys,
record.Item2.Values
}).ToArray();
return recordFields;
}


But its failed, is there any way?

EDIT:
Type of
_recordMasterList


List<Tuple<string, Dictionary<string, string>>> _recordMasterList;

Answer

Create a string array instead of an object in the query, then the ToArray will return an array of arrays:

public string[][] GetRecordFields(string selectedRecord) {
  return (
    from record in _recordMasterList
    where record.Item1 == selectedRecord
    select new string[] {
      record.Item2.Keys,
      record.Item2.Values
    }
  ).ToArray();
}