LINQ - 多行作为字符串 [英] Linq - multiple rows as string

查看:172
本文介绍了LINQ - 多行作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有表,其中包含的用户名和另一个含有姓。一个用户可以拥有多个FirstNames:

Lets assume that I have Table which contains Username and the other one which contains FirstName. A single user can have multiple FirstNames:

我怎样才能获得其中包含的用户名和用逗号分隔的所有名字的记录?

How can I obtain a record which will contain Username and all first names separated by comma?

我。即

Users
id | Username
1 | Test

Names
UserId | FirstName
1 | Mike
1 | John

我想收到其中将包含一个记录

I would like to receive a record which will contain

测试,迈克,约翰

我怎么能这样做?

修改:如果哪些用户表将有哪些我想获得更多的列

Edit: What if Users table will have more columns which I want to get?

我。即

id | Username | Status
1  | Test     | Active

如何获得测试,主动,迈克,约翰

推荐答案

您可以使用 GROUPBY 的string.join

var userGroups = from u in users
     join n in names
     on u.ID equals n.UserID
     group new{n, u} by n.UserID into UserGrp
     select new
     {
         Username = UserGrp.Key,
         Status = UserGrp.First().u.Status,
         Names = string.Join(",", UserGrp.Select(x => x.n.Name))
     };

foreach (var ug in userGroups)
   Console.WriteLine("{0}, {1}, \"{2}\"", ug.Username, ug.Status, ug.Names);

这篇关于LINQ - 多行作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆