简体   繁体   English

如何使用Linq在列表中找到属性值不同的第一项?

[英]How can I find the first items in a list with a different value for a property using Linq?

I have an ordered list of objects, and I would like to find the index of each item where a property changes, and get a dictionary/list of pairs matching index to property. 我有一个对象的有序列表,我想找到属性更改的每个项目的索引,并获取将索引与属性匹配的字典/成对列表。 For example, finding the index of each new first letter in a list of words ordered alphabetically. 例如,在按字母顺序排列的单词列表中查找每个新的第一个字母的索引。

I can do this with a foreach loop: 我可以使用foreach循环来做到这一点:

Initials = new Dictionary<char, int>();
int i = 0;
foreach (var word in alphabeticallyOrderedList))
{
    if (!Initials.ContainsKey(word.First()))
    {
        Initials[word.First()] = i;
    }
    i++;
}

But I feel like there should be an elegant way of doing this with Linq. 但是我觉得应该使用Linq来做到这一点。

You could have the same functionality with LINQ by using the overload of Select that exposes the index and by using GroupBy + ToDictionary : 通过使用暴露索引的Select重载和GroupBy + ToDictionary ,可以使LINQ具有相同的功能:

 Initials = alphabeticallyOrderedList
    .Select((word, index) => new { Word = word, WordIndex = index })
    .GroupBy(x => x.Word[0])
    .ToDictionary(charGroup => charGroup.Key, charGroup => charGroup.First().WordIndex);

But to quote myself: 但引用我自己:

LINQ is not always more readable, especially when indexes are important. LINQ并非总是更具可读性,尤其是在索引很重要的情况下。 You also lose some debugging, exception handling and logging capabilities if you use a large LINQ query 如果使用大型LINQ查询,您还将失去一些调试,异常处理和日志记录功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM