linq todictionary方法及其元素的顺序

发布于 2025-02-10 02:56:55 字数 1105 浏览 0 评论 0原文

我有一个对象的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文