2012-03-02 3 views
0

Linq을 사용하여 줄이고 싶은 코드 조각이 있습니다. 결과 집합에 대한 추가 그룹화를 수행하고 중첩 된 Dictionary을 빌드하는 루프는 foreach() 루프의 일부입니다.복잡한 foreach 루프는 linq 단축 수 있습니까?

Linq 구문을 사용하면 가능합니까?

 var q = from entity in this.Context.Entities 
       join text in this.Context.Texts on new { ObjectType = 1, ObjectId = entity.EntityId} equals new { ObjectType = text.ObjectType, ObjectId = text.ObjectId} 
     into texts 
       select new {entity, texts}; 

     foreach (var result in q) 
     { 
      //Can this grouping be performed in the LINQ query above? 
      var grouped = from tx in result.texts 
        group tx by tx.Language 
        into langGroup 
        select new 
           { 
            langGroup.Key, 
            langGroup 
           }; 
      //End grouping 

      var byLanguage = grouped.ToDictionary(x => x.Key, x => x.langGroup.ToDictionary(y => y.PropertyName, y => y.Text)); 

      result.f.Apply(x => x.Texts = byLanguage); 
     } 

     return q.Select(x => x.entity); 

Sideinfo : 기본적으로 어떻게됩니까

모든 언어와 (1를 하드 코딩이 경우) 특정 개체 유형에 대한 모든 속성에 대해 "텍스트"를 선택하고 언어별로 그룹화되어 있다는 점이다. 사전은 모든 언어에 대해 작성된 다음 모든 속성에 대해 작성됩니다.

EntitiesTexts (사전)이라는 속성이 있습니다. Apply은 다음과 같은 사용자 지정 확장 방법입니다.

public static T Apply<T>(this T subject, Action<T> action) 
    { 
     action(subject); 
     return subject; 
    } 
+3

당신은 람다 표현식을 사용하여 yy''반복하는'.Foreach' 확장 방법을 사용할 수 있습니다 이름 후에 나의 유형을 ... 이름. 또한 q.ToList(); 앞에 그룹화를 수행하는 것이 더 좋습니다. 또한 * BETTER NAMING *! –

+0

당신은 내가 단지 수수께끼 였고 엔티티, 텍스트에 미쳐 버렸고 x, y, z를 입력하고 싶었던 람다를 작성하는 것에 대해 옳았습니다. – ReFocus

+0

그러나 그룹 토큰 쿼리는 어떻게 든 .ToDictionary 내에서 수행 될 수 있습니까? – ReFocus

답변

2

이 훨씬 간단하지 않습니까?

foreach(var entity in Context.Entities) 
{ 
    // Create the result dictionary. 
    entity.Texts = new Dictionary<Language,Dictionary<PropertyName,Text>>(); 

    // loop through each text we want to classify 
    foreach(var text in Context.Texts.Where(t => t.ObjectType == 1 
              && t.ObjectId == entity.ObjectId)) 
    { 
     var language = text.Language; 
     var property = text.PropertyName; 

     // Create the sub-level dictionary, if required 
     if (!entity.Texts.ContainsKey(language)) 
      entity.Texts[language] = new Dictionary<PropertyName,Text>(); 

     entity.Texts[language][property] = text; 
    } 
} 

때로는 오래된 foreach 루프가 작업을 훨씬 잘 수행합니다.

언어, PROPERTYNAME 및 텍스트 코드에서 어떤 유형이 없다, 그래서 나는

관련 문제