IT story

배열에서 값의 인덱스 찾기

hot-time 2020. 8. 7. 07:53
반응형

배열에서 값의 인덱스 찾기


linq를 사용하여 배열에서 값의 인덱스를 찾을 수 있습니까?

예를 들어,이 루프는 배열 내에서 키 인덱스를 찾습니다.

for (int i = 0; i < words.Length; i++)
{
    if (words[i].IsKey)
    {
        keyIndex = i;
    }
}

int keyIndex = Array.FindIndex(words, w => w.IsKey);

실제로 생성 한 사용자 정의 클래스에 관계없이 개체가 아닌 정수 인덱스를 얻습니다.


배열의 경우 다음을 사용할 수 있습니다 Array.FindIndex<T>.

int keyIndex = Array.FindIndex(words, w => w.IsKey);

목록의 경우 다음을 사용할 수 있습니다 List<T>.FindIndex.

int keyIndex = words.FindIndex(w => w.IsKey);

모든에 대해 작동하는 일반 확장 메서드를 작성할 수도 있습니다 Enumerable<T>.

///<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;
}

LINQ도 사용할 수 있습니다.

int keyIndex = words
    .Select((v, i) => new {Word = v, Index = i})
    .FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;

int keyIndex = words.TakeWhile(w => !w.IsKey).Count();

사용할 수있는 단어를 찾으려면

var word = words.Where(item => item.IsKey).First();

이것은 IsKey가 참인 첫 번째 항목을 제공합니다 (비가있을 경우 사용하고 싶을 수 있습니다. .FirstOrDefault()

항목과 색인을 모두 얻으려면 사용할 수 있습니다.

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();

이 시도...

var key = words.Where(x => x.IsKey == true);

내 IndexWhere () 확장 메서드 구현 (단위 테스트 포함)을 게시했습니다.

http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

사용법 예 :

int index = myList.IndexWhere(item => item.Something == someOtherThing);

이 솔루션은 msdn microsoft 에서 더 많은 도움을 받았습니다 .

var result =  query.AsEnumerable().Select((x, index) =>
              new { index,x.Id,x.FirstName});

query귀하의 toList()쿼리입니다.


int index = -1;
index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;

참고 URL : https://stackoverflow.com/questions/1764970/find-index-of-a-value-in-an-array

반응형