如何将多行合并为单个文本?

时间:2015-06-29 06:52:50

标签: c# sql linq

我想将电话号码分组到同一部分,如下所示:

section | phone
   1    | 1001
   1    | 1002
   2    | 1201
   2    | 1202

并将它们分组为:

section | phone
   1    | 1001, 1002
   2    | 1201, 1202

但我不知道如何摸索它们的语法。

我这个代码

var entgr = (from fx in MainOnline.MA_TelUsers
             where fx.TE_SectionID != null
             group fx by fx.TE_SectionID into id
             from ids in id.DefaultIfEmpty()
             select new 
             { 
                  Section = ids.TE_SectionID,
                  TelPhone = ids.TE_Phone                                         
             });

我如何对其进行分组并将其用于加入其他表?

3 个答案:

答案 0 :(得分:0)

尝试此查询

var entgr = (from fx in MainOnline.MA_TelUsers
                 where fx.TE_SectionID != null
                 group fx by fx.TE_SectionID into ids
                           select new
                           {
 Section = ids.TE_SectionID,
                      TelPhone =ids.Aggregate((a, b) => 
                                       new {TelPhone = (a.TelPhone + ", " + b.TelPhone ) }).TelPhone 

                           });

答案 1 :(得分:0)

https://msdn.microsoft.com/en-us/library/vstudio/bb397696.aspx

查看此链接。如果你想在单个linq查询中执行它,那么我希望不可能。

但在评估时你可以这样做

var ph = new List<Phone>();
            ph.Add(new Phone() { SectionId = 1, PhoneNumber = 1001 });
            ph.Add(new Phone() { SectionId = 1, PhoneNumber = 1002 });
            ph.Add(new Phone() { SectionId = 2, PhoneNumber = 1201 });
            ph.Add(new Phone() { SectionId = 2, PhoneNumber = 1202 });

            var results = ph.GroupBy(i => i.SectionId).Select(i=> new {i.Key, i});
            foreach (var phone in results)
            {
                int section = phone.Key;
                string phoneNos = string.Join(",",phone.i.Select(i=>i.PhoneNumber));
            }

答案 2 :(得分:0)

var entgr = (from fx in ph
                         group fx by fx.SectionId.ToString() into id
                         select new
                         {
                             Section = id.Key,
                             TelPhone = string.Join(", ",id.Select(s => s.PhoneNumber.ToString()))
                         });