2016-04-06 42 views
0

在代碼優化期間,我找到了在LINQ中使用foreach循環的方法。我想在沒有這個循環的情況下使用它。任何建議如何改變它?LINQ不使用週期

public IEnumerable<Tuple<string, string>> ListAllCoursesWithArea() 
{ 
    List<Tuple<string,string>> final = new List<Tuple<string, string>>(); 
    Tuple<string, string> tmp; 

    var books = (
    from temp in bookListLoader.LoadList() 
    group temp by new { temp.CourseCode } into g 
    select g.First() 
    ).ToList(); 

    foreach (BookListRecord i in books) 
    { 
     tmp = new Tuple<string, string>(i.CourseCode, i.Area); 
     final.Add(tmp); 
    } 
    return final; 
} 

我試過,但它給我的錯誤消息 「應爲標識符」:

public IEnumerable<Tuple<string, string>> ListAllCoursesWithArea() 
{ 
    var books = (
    from temp in bookListLoader.LoadList() 
    group temp by new { temp.CourseCode } into g 
    select g.First().(new Tuple<g.CourseCode,g.Area>()) 
    ).ToList(); 
    return books; 
} 

回答

1

可讀和最短路徑:

public IEnumerable<Tuple<string, string>> ListAllCoursesWithArea() 
{ 
    return bookListLoader 
       .LoadList() 
       .GroupBy(x => x.CourseCode) 
       .Select(g => g.First()) 
       .Select(x => new Tuple<string, string>(x.CourseCode, x.Area)); 
} 

或者在你的榜樣:

public IEnumerable<Tuple<string, string>> ListAllCoursesWithArea() 
{ 
    return from temp in bookListLoader.LoadList() 
      group temp by new { temp.CourseCode } into g 
      let x = g.First() 
      select new Tuple<string, string>(x.CourseCode, x.Area); 

} 
+0

可能可以將2個選擇變成單個選擇多個。 – code4life

+0

@ code4life可能是的,但在這種情況下,我們需要評估'First()'兩次,不需要我們嗎? –

+0

不,我認爲你可以用'First()'創建Tuple。 – code4life