2009-11-16 4 views
1

LINQ를 사용하여 반복없이 수행하는 방법은 무엇입니까?LINQ를 사용하여 마지막 반복에서 매개 변수를 가져옵니다.

string[] flatSource = {"region1", "subregion1", 
         "region2", "sub1", "sub2", 
         "region3", "sub1", "sub2"}; 

string previousRegion = ""; 
foreach (var item in flatSource) 
{ 
    if (SomeRegionDictionary.Contains(item)) 
     previousRegion = item; //This is what I can't figure out 
    else 
     yield return new SubregionWithRegion{Region = previousRegion, SubRegion = item}; 
} 

답변

3

현재 해결책은 정상입니다. LINQ는 그러한 상태 저장 쿼리에 이상적인 선택이 아닙니다. 여기에 순수 LINQ 솔루션이 있습니다. 이 차의 복잡성을 가진 작은 비밀이기 때문에 이상적인 아니지만, 기능적으로 동일하다 :

return flatSource.Select((item, index) => 
        new SubregionWithRegion 
        { 
         Region = flatSource.Take(index + 1) 
              .LastOrDefault(SomeRegionDictionary.ContainsKey) ?? "", 
         SubRegion = item 
        }) 
        .Where(srwr => !SomeRegionDictionary.ContainsKey(srwr.SubRegion)); 

루프의 상태 특성은 Take + LastOrDefault 쿼리를 처리하고 까다로운 else 조건 처리 최종 Where 절.

2

나는 신중하게 질문을 읽지 않았던 것 같습니다. 따라서 아래의 확장은 유용 할 수 있지만이 질문에는 유용하지 않을 수 있습니다.

public static class IEnumerableOfTExtensions 
{ 
    public static T Before<T>(this IEnumerable<T> source, Func<T, bool> condition) 
    { 
     if (source == null) 
      throw new ArgumentNullException("source"); 

     if (condition == null) 
      throw new ArgumentNullException("condition"); 

     using (var e = source.GetEnumerator()) 
     { 
      var first = true; 
      var before = default(T); 

      while (e.MoveNext()) 
      { 
       if (condition(e.Current)) 
       { 
        if (first) 
         throw new ArgumentOutOfRangeException("condition", "The first element corresponds to the condition."); 

        return before; 
       } 

       first = false; 
       before = e.Current; 
      } 
     } 

     throw new ArgumentOutOfRangeException("condition", "No element corresponds to the condition."); 
    } 
} 
+0

:

return flatSource.Where(i=>SomeRegionDictionary.Contains(i)).Zip(arr.Skip(1), (first, second) => new SubregionWithRegion{Region = first, SubRegion = second}); 

당신이 인터넷 4.0이없는 경우에는이 구현을 사용할 수 있습니다 검색어는 OP의 원래 질문을 해결할 수있는 곳이면 어디에서나 찾을 수 있습니까? – Ani

+0

@Ani : 네 말이 맞아. 나는 그 질문을 충분히주의 깊게 읽지 않았다. 그래서 저는 여기서 제 대답을 드리겠습니다.하지만 당신의 문제는 구체적인 문제를 해결하는 것처럼 보입니다. – Oliver

1

당신은 인터넷 4.0 우편 번호와 함께 한 성명에서 그것을 할 수 있습니다 : 최종 작업을 수행하는 방법 Zip Me Up

관련 문제