在LINQ中将多行连接成一行

时间:2012-09-05 07:48:51

标签: c# .net 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 个答案:

答案 0 :(得分:7)

不确定

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

注意:结果将是匿名类型。我们无法在此处重复使用sample类,因为该类list的类型为List<int>而非string

如果您坚持使用.NET 3.5或更低版本,请改用此代码:

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

如果要在获取字符串之前对列表进行排序,则需要使用此代码:

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

答案 1 :(得分:0)

由于我需要在一列中收集多个记录(每个员工可能有很多专业)然后在加入中使用它,这就是我解决的方式:

拥有这些实体:

1)员工实体

|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;

我希望这可以帮助别人!