LINQ 字典到锯齿状数组?
有一个方法返回 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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在查询中创建一个字符串数组而不是一个对象,然后
ToArray
将返回一个数组数组:Create a string array instead of an object in the query, then the
ToArray
will return an array of arrays:在您的
select
中,您需要创建一个字符串数组 (new []
)。在您的示例中,您正在创建一个新的匿名类型。(我稍微更改了代码以处理
Dictionary
类型的_recordMasterList
。此外,在这样的代码中,我发现声明变量更加清晰显式键入,而不是依赖隐式键入。我更喜欢使用隐式数组类型 -new []
而不是new string[]
。)In your
select
you need to create a string array (new []
). In your example you were creating a new anonymous type.(I've changed the code slightly to deal with a
_recordMasterList
of typeDictionary<string, string>
. Also, in code like this I find it clearer to declare my variable type explicitly, rather than relying on implicit typing. That said, with arrays I prefer to use implicit array typing -new []
rather thannew string[]
.)这不是单行 LINQ 魔法,但它是:
Not a one liner LINQ magic but here it is:
具有相反尺寸的更通用版本:
A more generic version with reversed dimensions:
你的问题还是有点令人困惑。这是您正在寻找的行为吗?
(我知道这个答案可以优化很多,但它似乎是弄清楚你想要什么的最简单方法。)
Your question is still a little bit confussing. Is this the behaviour you are looking for?
(I know that this answer could be optimised a lot, but it seams the easiest way to figue out what you want.)