LINQ

2012-06-04 2 views
1

을 사용하는 특정 기준에 따라 목록의 목록 항목 위치 찾기 허용되는 답변이 개체 수준에서 평가된다는 점을 제외하고는 linq find in which position is my object in List과 유사합니다. LINQ

내가과 같이 IFoo의 목록 컬렉션이 지금

public interface IFoo{ 
    string text {get;set;} 
    int number {get;set;} 
} 

public class Foo : IFoo{ 
    public string text {get;set;} 
    public int number {get;set;} 
} 

이 말 : 내가 다시 가져 오는 방법을 쓰고 싶어

public IList<IFoo> Foos; 

속성 값 및/또는 값에 기초하여 Foos의 인덱스 (예 :이 경우 686,또는 number는) 그래서 내가 좋아하는 뭔가를 할 수 있습니다

var fooIndexes = Foos.GetIndexes(f => f.text == "foo" && f.number == 8); 

나는 그을 작성하는 방법?

답변

4

당신은 같은 것을 사용할 수 있습니다

public static IEnumerable<int> GetIndices<T>(this IEnumerable<T> items, Func<T, bool> predicate) 
{ 
    return items.Select((item, index) => new { Item = item, Index = index }) 
        .Where(p => predicate(p.Item)) 
        .Select(p => p.Index); 
} 
1

을 여기에 비 LINQ 구현 : 그것은 익명 타입 초기화를 피할 수 있기 때문에

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

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

     i++; 
    } 
} 

이 경우, 이것은 아마도 더 효율적으로 될 것입니다.