web-dev-qa-db-ja.com

LINQを使用してインデックスを取得する方法

そのようなデータソースがあるとします。

var c = new Car[]
{
  new Car{ Color="Blue", Price=28000},
  new Car{ Color="Red", Price=54000},
  new Car{ Color="Pink", Price=9999},
  // ..
};

LINQで特定の条件を満たす最初の車のインデックスを見つける方法を教えてください。

編集:

私はこのようなことを考えることができましたが、それはひどく見えます:

int firstItem = someItems.Select((item, index) => new    
{    
    ItemName = item.Color,    
    Position = index    
}).Where(i => i.ItemName == "purple")    
  .First()    
  .Position;

これを単純な古いループで解決するのが最善でしょうか。

289
codymanix

IEnumerableは順序付き集合ではありません。
ほとんどのIEnumerableは順序付けされていますが、いくつか(DictionaryHashSetなど)は順序付けられていません。

したがって、LINQにはIndexOfメソッドはありません。

しかし、あなたは自分で書くことができます:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
    if (items == null) throw new ArgumentNullException("items");
    if (predicate == null) throw new ArgumentNullException("predicate");

    int retVal = 0;
    foreach (var item in items) {
        if (predicate(item)) return retVal;
        retVal++;
    }
    return -1;
}
///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }
121
SLaks
myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;

または少し短い

myCars.Select((car, index) => new {car, index}).First(myCondition).index;
628

簡単に

int index = List.FindIndex(your condition);

例えば。

int index = cars.FindIndex(c => c.ID == 150);
121
Red Swan
myCars.TakeWhile(car => !myCondition(car)).Count();

できます!それについて考えてください。最初に一致したアイテムのインデックスは、その前の(一致しない)アイテムの数と同じです。

ストーリータイム

私もあなたの質問であなたがすでに提案した恐ろしい標準解が嫌いです。受け入れられた答えのように、私はわずかな修正を伴うけれども私は明白な古いループに行きました:

public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
    int index = 0;
    foreach (var item in items) {
        if (predicate(item)) break;
        index++;
    }
    return index;
}

一致しない場合は-1ではなく項目数を返すことに注意してください。しかし、今のところ、この小さな煩さを無視しましょう。実際には恐ろしい標準的な解決策がクラッシュし、 範囲外の優れたインデックス を返すことを検討します。

今起きていることは、ReSharperが私に言っている ループはLINQ式 に変換することができる。ほとんどの場合、この機能は読みやすさを悪化させますが、今回の結果は驚くべきものでした。だからJetBrainsに称賛を。

分析

長所

  • 簡潔
  • 他のLINQと組み合わせ可能
  • 匿名オブジェクトのnewingを回避します
  • 述語が最初に一致するまで、列挙型を評価するだけです

したがって、読みやすさを保ちながら、時間と空間の両面で最適と考えます。

短所

  • 最初はあまり明白ではありません
  • 一致がない場合は-1を返しません

もちろん、あなたはいつでもそれを拡張メソッドの背後に隠すことができます。そして、何も一致しないときに最善を尽くすには、状況に大きく依存します。

76
LumpN

私はここで私の貢献をするつもりです...なぜですか?理由は次のとおりです。p Any LINQ拡張機能とデリゲートに基づく、異なる実装。ここにあります:

public static class Extensions
{
    public static int IndexOf<T>(
            this IEnumerable<T> list, 
            Predicate<T> condition) {               
        int i = -1;
        return list.Any(x => { i++; return condition(x); }) ? i : -1;
    }
}

void Main()
{
    TestGetsFirstItem();
    TestGetsLastItem();
    TestGetsMinusOneOnNotFound();
    TestGetsMiddleItem();   
    TestGetsMinusOneOnEmptyList();
}

void TestGetsFirstItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("a"));

    // Assert
    if(index != 0)
    {
        throw new Exception("Index should be 0 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsLastItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("d"));

    // Assert
    if(index != 3)
    {
        throw new Exception("Index should be 3 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnNotFound()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d" };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMinusOneOnEmptyList()
{
    // Arrange
    var list = new string[] {  };

    // Act
    int index = list.IndexOf(item => item.Equals("e"));

    // Assert
    if(index != -1)
    {
        throw new Exception("Index should be -1 but is: " + index);
    }

    "Test Successful".Dump();
}

void TestGetsMiddleItem()
{
    // Arrange
    var list = new string[] { "a", "b", "c", "d", "e" };

    // Act
    int index = list.IndexOf(item => item.Equals("c"));

    // Assert
    if(index != 2)
    {
        throw new Exception("Index should be 2 but is: " + index);
    }

    "Test Successful".Dump();
}        
12

これは私がまとめたちょっとした拡張です。

public static class PositionsExtension
{
    public static Int32 Position<TSource>(this IEnumerable<TSource> source,
                                          Func<TSource, bool> predicate)
    {
        return Positions<TSource>(source, predicate).FirstOrDefault();
    }
    public static IEnumerable<Int32> Positions<TSource>(this IEnumerable<TSource> source, 
                                                        Func<TSource, bool> predicate)
    {
        if (typeof(TSource) is IDictionary)
        {
            throw new Exception("Dictionaries aren't supported");
        }

        if (source == null)
        {
            throw new ArgumentOutOfRangeException("source is null");
        }
        if (predicate == null)
        {
            throw new ArgumentOutOfRangeException("predicate is null");
        }
        var found = source.Where(predicate).First();
        var query = source.Select((item, index) => new
            {
                Found = ReferenceEquals(item, found),
                Index = index

            }).Where( it => it.Found).Select( it => it.Index);
        return query;
    }
}

それならあなたはそれをこのように呼ぶことができます。

IEnumerable<Int32> indicesWhereConditionIsMet = 
      ListItems.Positions(item => item == this);

Int32 firstWelcomeMessage ListItems.Position(msg =>               
      msg.WelcomeMessage.Contains("Hello"));
4
jwize

これは、項目が見つからないときに-1を返す、最高得票数の回答の実装です。

public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
    var itemsWithIndices = items.Select((item, index) => new { Item = item, Index = index });
    var matchingIndices =
        from itemWithIndex in itemsWithIndices
        where predicate(itemWithIndex.Item)
        select (int?)itemWithIndex.Index;

    return matchingIndices.FirstOrDefault() ?? -1;
}
3
Sam