获取所有匹配项的索引 [英] Getting indexes of all matching items

查看:43
本文介绍了获取所有匹配项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取枚举中与给定条件匹配的所有项目的索引.有没有比这更清洁的方法了?

I want to get the index of all items in an enumerable that match a given condition. Is there a cleaner way than this?

var indexes = list.Select((item, index) => new { Item = item, Index = index }).Where(o => Condition(o.Item)).Select(o => o.Index);

推荐答案

使用标准LINQ to Object方法-不,没有.您只能通过将查询分成几行来提高可读性:

Using standard LINQ to Object methods - no, there's not. You only can improve readability by splitting your query into couple lines:

var indexes = list.Select((item, index) => new { Item = item, Index = index })
                  .Where(o => Condition(o.Item))
                  .Select(o => o.Index);

但是,您可以为此编写扩展方法:

However, you can write an Extension Method for that:

public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    int index=0;
    foreach (T element in source)
    {
        if (predicate(element))
        {
            yield return index;
        }
        index++;
    }
}

这篇关于获取所有匹配项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆