17

アイテム{10、11、23、34、56、43}を含むintのリストがあり、23より大きいすべてのアイテムのインデックスを調べたい。これらの値は任意の順序にすることができるので、それらを並べ替えます。

List<int> mylist = new List<int> { 10, 11, 23, 34, 56, 43 };

条件を満たす最初のアイテムだけでなく、条件を満たすすべてのアイテムのインデックスに興味があります。したがって、このコード行は私には機能しません。

int index = mylist.FindIndex( x => x > 23 );
4

4 に答える 4

26
var indexes = mylist.Select((v, i) => new { v, i })
                    .Where(x => x.v > 23)
                    .Select(x => x.i);
于 2013-01-23T09:25:16.803 に答える
1

Linq はそのようなものを直接提供していませんが、独自のものを作成できます。このようなもの:

public static IEnumerable<int> FindIndices<T>(this IEnumerable<T> items, Func<T, bool> predicate) 
{
    int i = 0;

    foreach (var item in items) 
    {
        if (predicate(item)) 
        {
            yield return i;
        }

        i++;
    }
}

次に、次のようなものです。

foreach (int index in mylist.FindIndices( x => x > 23 ))
    ...

(これには、上記の他のアプローチよりも効率的であるという利点があります。ただし、これは大きなシーケンスの場合にのみ重要です!)

于 2013-01-23T09:26:51.227 に答える
0

この拡張メソッドは、素晴らしくクリーンな仕事をします:

public static class ListExtensions
{
    /// <summary>
    /// Finds the indices of all objects matching the given predicate.
    /// </summary>
    /// <typeparam name="T">The type of objects in the list.</typeparam>
    /// <param name="list">The list.</param>
    /// <param name="predicate">The predicate.</param>
    /// <returns>Indices of all objects matching the given predicate.</returns>
    public static IEnumerable<int> FindIndices<T>(this IList<T> list, Func<T, bool> predicate)
    {
        return list.Where(predicate).Select(list.IndexOf);
    }
}

動作デモをチェックしてください

于 2013-01-23T09:27:18.473 に答える
0

rgripper の 答えの小さなバリエーション、

List<int> mylist = new List<int> { 10, 11, 23, 34, 56, 43 };
List<int> newList = mylist.Select((v, i) => new { v, i })
                        .Where(x => x.v > 23)
                        .Select(x => x.i).ToList<int>();

デモ

于 2013-01-23T09:33:15.893 に答える