1

是否可以将多行连接到单行?

例如:

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

这意味着从列表中新行现在是一个字符串。

4

2 回答 2

7

当然:

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

注意:结果将是匿名类型。我们不能在sample这里重用这个类,因为那个类list是 typeList<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))
                });
于 2012-09-05T07:52:02.463 回答
0

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

拥有这些实体:

1) 员工实体

|EMPLOYEE_ID|

|001        |

|002        |    

2) EMPLOYEE_SPECIALTIES 实体

|EmployeeId|SPECIALTY_CODE

|001       |AAA

|001       |BBB

|002       |DDD

|002       |AAA

我需要在一个列中按员工收集专业:

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

我希望这可以帮助某人!

于 2016-10-03T13:50:09.660 回答