linq todictionary方法及其元素的顺序
我有一个对象的iEnumerable
,我需要将其变成过滤的字典。字典的键必须是对象的名称,该值必须是其属性之一。我使用linq的toString
方法:
// dataPoints is of type IEnumerable
var filteredDictionary = dataPoints.Where(d => d.TypeName == typeNameOfInterest).ToDictionary(d => d.Name, d => d.Identifier)
我最终将字典变成字符串,如下所示:
string.Join(Environment.NewLine, filteredDictionary.Select(d => $"{d.Key} : {d.Value};").ToArray()))
此操作和字符串中元素的顺序与iEnumerable中的顺序相同/代码>。 i think 那是文档是指关于返回的字典的以下内容
每个组中的值与源
中的顺序相同
,我需要从字典中获取第一个元素。首先,我的意思是原始iEnumerable
中列出的第一个。我需要怎么做?我可以依靠linq的第一个
方法来确保它是正确的吗?在获得第一个元素之前,我需要构造sortedDictionary
吗?
我正在使用.NET Framework 4.7.2,但我从不修改我从todictionary
中收到的字典的内容。
I have an IEnumerable
of objects which I need to turn into a filtered dictionary. The key of the dictionary must be the object's name and the value must be one of its properties. I do so using LINQ's ToString
method:
// dataPoints is of type IEnumerable
var filteredDictionary = dataPoints.Where(d => d.TypeName == typeNameOfInterest).ToDictionary(d => d.Name, d => d.Identifier)
I eventually turn the dictionary into a string as follows:
string.Join(Environment.NewLine, filteredDictionary.Select(d => quot;{d.Key} : {d.Value};").ToArray()))
This works and the order of the elements in the string is the same as the order in the IEnumerable
. I think that is what the documentation means by stating the following about the returned dictionary
The values within each group are in the same order as in source
Now, I need to get the first element from the dictionary. By first I mean the first one listed in the original IEnumerable
. How would I need to do this? Can I rely on LINQ's first
method to do so and be sure that it is the correct one? Would I need to construct a SortedDictionary
before getting the first element?
I'm using the .NET Framework 4.7.2 and I never modify the content of the dictionary that I receive from ToDictionary
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论