有一个返回 2D 数组的方法,此方法从 LINQ 查询查询字典并尝试将键和值存储在 2D 数组中。
但我做不到
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;
}
但它失败了,有什么办法吗?
编辑:_recordMasterList
类型
List<Tuple<string, Dictionary<string, string>>> _recordMasterList;
在查询中创建一个字符串数组而不是一个对象,则ToArray
将返回一个数组数组:
public string[][] GetRecordFields(string selectedRecord) {
return (
from record in _recordMasterList
where record.Item1 == selectedRecord
select new string[] {
record.Item2.Keys,
record.Item2.Values
}
).ToArray();
}
在你的select
中,你需要创建一个字符串数组(new []
)。在您的示例中,您正在创建一个新的匿名类型。
public string[][] GetRecordFields(string selectedRecord)
{
string[][] recordFields = (from record in _recordMasterList
where record.Key == selectedRecord
select new []
{
record.Key,
record.Value
}).ToArray();
return recordFields;
}
(我稍微更改了代码以处理 Dictionary<string, string>
类型的_recordMasterList
。此外,在这样的代码中,我发现显式声明我的变量类型比依赖隐式类型更清晰。也就是说,对于数组,我更喜欢使用隐式数组类型 - new []
而不是new string[]
。
不是单行 LINQ 魔法,但这里是:
/// <summary>
/// Converts dictionary to 2d string array
/// </summary>
/// <param name="Dictionary">Dictionary to be converted</param>
/// <returns>2D string Array</returns>
private string[,] ConvertDictionaryTo2dStringArray(Dictionary<string, string> Dictionary)
{
string[,] stringArray2d = new string[2, Dictionary.Count];
int i = 0;
foreach (KeyValuePair<string, string> item in Dictionary)
{
stringArray2d[0, i] = item.Key;
stringArray2d[1, i] = item.Value;
i++;
}
return stringArray2d;
}
具有反向尺寸的更通用版本:
private object[,] Dictionary2Array(Dictionary<object, object> dic)
{
object[,] arr = new object[dic.Count, 2];
int i = 0;
foreach (KeyValuePair<object, object> item in dic)
{
arr[i, 0] = item.Key;
arr[i, 1] = item.Value;
i++;
}
return arr;
}
你的问题仍然有点令人困惑。 这是您要找的行为吗?
(我知道这个答案可以优化很多,但它是找出你想要什么的最简单方法。
public string[,] GetRecordFields(string selectedRecord)
{
//List<Tuple<string, Dictionary<string, string>>> _recordMasterList;
List<Dictionary<string, string>> selectedRecords
= (from record in _recordMasterList
where record.Item1 == selectedRecord
select record.Item2)
.ToList();
int totalNumberOfRecords = 0;
foreach(Dictionary<string, string> d in selectedRecords)
{
totalNumberOfRecords += d.Count();
}
string[,] result = new string[2, totalNumberOfRecords];
int i = 0;
foreach(Dictionary<string, string> d in selectedRecords)
{
foreach(KeyValuePair<string, string> kvp in d)
{
result[0,i] = kvp.Key;
result[1,i] = kvp.Value;
ii++;
}
}
return result;
}