2012-09-05 64 views
0

可以將多行連接到單個行嗎?在LINQ中將多個行連接成單個行

例如:

IEnumerable<sample> sam = new List<sample>() 
{ 
    new sample{ id = 1, name = "sample 1", list = new List<int>{1,5,6}}, 
    new sample{ id = 2, name = "sample 2", list = new List<int>{2,9}}, 
    new sample{ id = 3, name = "sample 3", list = new List<int>{8,3,7}}, 
    new sample{ id = 4, name = "sample 4", list = new List<int>{3,4,8}}, 
    new sample{ id = 5, name = "sample 5", list = new List<int>{1,5,7}}, 
    new sample{ id = 6, name = "sample 6", list = new List<int>{6,9,7}} 
}; 

輸出必須:

{ 
    new sample { id = 1, name = "sample 1", list = "1,5,6" }, 
    new sample { id = 2, name = "sample 2", list = "2,9" }, 
    new sample { id = 3, name = "sample 3", list = "8,3,7" }, 
    new sample { id = 4, name = "sample 4", list = "3,4,8" }, 
    new sample { id = 5, name = "sample 5", list = "1,5,7" }, 
    new sample { id = 6, name = "sample 6", list = "6,9,7" } 
}; 

,從列表意味着現在新行是一個字符串。

+2

由於'list'可以被定義爲一個'List '或一個'string',而不是兩者,否則你將無法返回'樣本',但否則這是相當微不足道的LINQ。 – Rawling

回答

6

肯定的:

sam.Select(x => new { x.id, x.name, list = String.Join(",", x.list) }); 

注意:結果將是一個匿名類型。我們不能在這裏重新使用sample類,因爲在那個類中list的類型是List<int>而不是string。如果你想對列表進行排序

sam.Select(x => new 
       { 
        x.id, x.name, 
        list = String.Join(",", x.list.Select(y => y.ToString()) 
                .ToArray()) 
       }); 

你需要使用此代碼獲取字符串之前:

如果你被卡住.NET 3.5或更低,使用此代碼,而不是

sam.Select(x => new 
       { 
        x.id, x.name, 
        list = String.Join(",", x.list.OrderBy(y => y)) 
       }); 
+0

String.Join需要一個'string []',而不是'List '。 – Rawling

+2

@Rawling:從4.0開始接受'IEnumerable ' – abatishchev

+0

@Rawling:String.Join有幾個重載。我的代碼使用這一個:http://msdn.microsoft.com/en-us/library/dd992421.aspx –

0

由於我需要在一列中收集多個記錄(每個員工可能有許多特色),然後在連接中使用它,這是我解決的方法:

擁有這些實體:

1)Employees實體

|EMPLOYEE_ID| 

|001  | 

|002  |  

2)EMPLOYEE_SPECIALTIES實體

|EmployeeId|SPECIALTY_CODE 

|001  |AAA 

|001  |BBB 

|002  |DDD 

|002  |AAA 

我需要收集由僱員特色在一個columun:

|EmployeeId|SPECIALTY_CODE 

|001  |AAA, BBB 

|002  |DDD, AAA 

解決方案:

var query = from a in context.EMPLOYEE_SPECIALTIES.ToList() 
      group a by a.EMPLOYEE_ID into g 
      select new 
      { 
       EmployeeId = g.Key, 
       SpecialtyCode = string.Join(",", g.Select(x => 
       x.SPECIALTY_CODE)) 
      }; 

var query2 = (from a in query 
       join b in context.EMPLOYEEs on a.EmployeeId equals b.EMPLOYEE_ID 
       select new EmployeeSpecialtyArea 
       { 
        EmployeeId = b.EMPLOYEE_ID, 
        LastName = b.LAST_NAME, 
        SpecialtyCode = a.SpecialtyCode 
       }); 

ViewBag.EmployeeSpecialtyArea = query2; 

我希望這可以幫助別人!