'indexOf'에 해당되는 글 1건

  1. 2012.01.30 [wp7] List의 선택한 값의 Index값을 알고 싶을때 IndexWhere
Windows Phone 72012. 1. 30. 20:39

코레일을 하다가 index값을 구해야 하는 경우가 생겼다.

하지만 Linq에서 where 문을 이용해서 firstOrDefault()를 이용해서 값을 얻어 왔지만 그 값이 List의 몇번째 값인지는

알수 없었다. 다른데서는 지원되는데 윈폰7의 compact .net framework에서는 제공되지 않는것인가? ㅠㅠ

그래서 여러가지 방법중 좋은 방법을 찾았다.

그 방법은 바로..두구두구두구..

그냥 직접 제작하는것이다 하하하

일단 구현한 클래스는 이렇다.

using System;
using System.Collections.Generic;

namespace GloryApp.Utils
{
    public static class IEnumerableExtensions
    {
        public static int IndexWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
        {
            var enumerator = source.GetEnumerator();

            int index = 0;

            while (enumerator.MoveNext())
            {
                TSource obj = enumerator.Current;

                if (predicate(obj))

                    return index;

                index++;
            }

            return -1;
        }

        public static int IndexWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
        {
            var enumerator = source.GetEnumerator();

            int index = 0;

            while (enumerator.MoveNext())
            {
                TSource obj = enumerator.Current;

                if (predicate(obj, index))

                    return index;

                index++;
            }

            return -1;
        }
    }
}

 

그리고 위의 프레임워크를 사용할 클래스에 using 하면

var temp = siList.IndexWhere(c => c.h_srcar_no == currenSrcarNo);

이런식으로 얻어 올수 있다.

 

참고 : http://snipplr.com/view/53625/

Posted by 동동(이재동)