2016-05-15 92 views
1

在Linq中對此有一些問題。我有一個記錄列表如下圖所示:使用linq根據不同的第二列從一列中選擇所有值

var allTeams = new List<AllTeamData>() 
{ 
    new AllTeamData { Team = "Bengals", Conference = "AFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Steelers", Conference = "AFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Patriots", Conference = "AFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Bills", Conference = "AFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Dolphins", Conference = "AFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Lions", Conference = "NFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Bears", Conference = "NFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Seahawks", Conference = "NFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Cardinals", Conference = "NFC", ConferenceEmail = "[email protected]" }, 
    new AllTeamData { Team = "Vikings", Conference = "NFC", ConferenceEmail = "[email protected]" } 
}; 

什麼,我試圖做的是這種形式建立一個記錄列表:

public class ConferenceData 
{ 
    public string Conference { get; set; } 
    public string ConferenceEmail { get; set; } 
    public List<string> Teams { get; set; } 
} 

什麼我試圖做的是用特定會議中的團隊名單發送電子郵件到特定的會議電子郵件。這是我已經能夠用我的linq查詢得到:

var conferences = (from t in allTeams 
          select new ConferenceData 
          { 
           Conference = t.Conference, 
           ConferenceEmail = t.ConferenceEmail 
          }).Distinct().ToList(); 

希望這一切都有道理。我試圖找出是否需要放置一個嵌套查詢來拉動所有團隊並將其放入該對象列表中。不知道如何去做。任何見解都會很棒。

+0

看看如何使用LINQ'GroupBy' – Nkosi

回答

0

使用GroupBygroup clause (C# Reference)

var conferences = (from t in allTeams 
        group t by new { t.Conference, t.ConferenceEmail } into g 
        select new ConferenceData { 
         Conference = g.Key.Conference, 
         ConferenceEmail = g.Key.ConferenceEmail, 
         Teams = g.Select(t => t.Team).ToList() 
        }).Tolist(); 

下面是使用GroupBy

conferences = allTeams.GroupBy(t => new { t.Conference, t.ConferenceEmail }) 
       .Select(g => new ConferenceData { 
        Conference = g.Key.Conference, 
        ConferenceEmail = g.Key.ConferenceEmail, 
        Teams = g.Select(t => t.Team).ToList() 
       }).Tolist(); 
+0

我從格蘭特和你們倆體會到信息相同恩科西。我可能會使用組合子句的用法。我之前正在研究這個問題,但不知道如何像你所做的那樣制定這個條款。 – Dean

1

如果您正在編寫SQL查詢,您將嘗試按特定字段對記錄進行分組。

同樣,LINQ有一個GroupBy方法,使您可以將數據分組的會議:

var conferences = allTeams.GroupBy(t => t.Conference) 
          .Select(grp => new ConferenceData 
             { 
              Conference = grp.Key, 
              ConferenceEmail = grp.First().ConferenceEmail, 
              Teams = grp.Select(x => x.Team).ToList() 
             }) 
          .ToList(); 

我在方法的語法寫了這個,因爲這就是我比較熟悉,但你可以把它翻譯成查詢語法(類似於你當前的查詢),如果你這麼傾向的話。

相關問題