将2行转换为一行

时间:2014-02-11 00:43:43

标签: c# sql linq

我在网格中显示以下数据。

ID     Name   Address
-----------------------------------------
1      Mike     100, Francis Dr, PA
1      Mike      2, Richmond Street, PA
2      John     45, Francis Dr, PA
2      John     55, Richmond Street, PA
3      Peter    23, Castle Street, PA

如何将address2转换为Telerik网格中的新列或linq查询并显示如下 -

ID     Name   Home-Address            Office-Address
------------------------------------------------------------------------------
1      Mike     100, Francis Dr, PA      2, Richmond Street, PA
2      John     45, Francis Dr, PA        55, Richmond Street, PA
3      Peter    23, Castle Street, PA

2 个答案:

答案 0 :(得分:1)

这将向您展示如何使用Addr1和Addr2进行操作,因为上面的注释说明您在呈现数据时无法知道订单,因此您无法知道哪些是有效的,哪些是在家。

void Main()
{
   List<record> data = new List<record> {
    new record() { ID = 1, Name = "Mike", Address = "100, Francis Dr, PA" },
    new record() { ID = 1, Name = "Mike", Address = "2, Richmond Street, PA" },
    new record() { ID = 2, Name = "John", Address = "45, Francis Dr, PA" },
    new record() { ID = 2, Name = "John", Address = "55, Richmond Street, PA" },
    new record() { ID = 3, Name = "Peter", Address = "23, Castle Street, PA" } };

   var result
     = data.GroupBy((x) => new { ID =x.ID, Name = x.Name })
        .Select((x) => 
           new { ID = x.Key.ID,
                 Name = x.Key.Name,
                 Addr1 = x.Take(1).Select((z) => z.Address).FirstOrDefault(),
                 Addr2 = x.Skip(1).Select((z) => z.Address).FirstOrDefault()});

}

// Define other methods and classes here
public class record
{
   public int ID { get; set; }
   public string Name { get; set; }
   public string Address { get; set; }
}

缩小以适应细柱。

LinqPad的结果:

enter image description here

您还可以通过将Addr行替换为:

来创建分隔列表
 Alist = string.Join("||",x.Select((z) => z.Address))});

看起来像这样:

enter image description here

答案 1 :(得分:0)

我假设你的第一个地址是家庭地址,第二个地址是办公室地址,还有一个直接表。在这种情况下,写一个SP并将其分配给telerik数据源

select t1.ID, t1.Name, t1.Home_Address, t2.Office_Address
(select ID,Name,Address as Home_Address 
from
(select ID,Name,Address,row_number() over (partition by ID Order by ID) rnum
from table_name) a
where a.rnum=1 ) t1 
left join
(select ID,Name,Address as Office_Address from
(select ID,Name,Address,row_number() over (partition by ID Order by ID) rnum
from table_name) b 
where b.rnum=2) t2
on t1.ID=t2.ID