SELECT Parent, Child FROM Daycare_Contacts
GROUP BY Parent, Child;
返回类似
的结果集Parent Child
Bob Brett
Bob Cindy
Bob John
Alice Pierre
Alice John
我希望将子元素作为逗号分隔列表返回,并将不同的父元素作为相邻列。像这样:
Parent Child
Bob Brett, Cindy, John
Alice Pierre, John
如果可以在LINQ中完成,我也会对此持开放态度。
答案 0 :(得分:4)
1)您可以从T-SQL返回逗号分隔的数据。
为此目标,您需要使用FOR XML命令。
您可以查看详细信息here。
请检查下一个T-SQL脚本:
DECLARE @Daycare_Contacts TABLE
(
Parent VARCHAR(100),
Child VARCHAR(100)
)
INSERT INTO @Daycare_Contacts
VALUES ('Bob', 'Brett'), ('Bob', 'Cindy'), ('Bob', 'John'), ('Alice', 'Pierre'), ('Alice', 'John')
SELECT
Parent,
STUFF((SELECT ', ' + Child AS 'text()' FROM @Daycare_Contacts t WHERE t.PArent = dc.Parent FOR XML PATH('')), 1, 2, '') AS Childs
FROM @Daycare_Contacts dc
GROUP BY Parent;
结果:
Parent Childs
--------------------------
Alice Pierre, John
Bob Brett, Cindy, John
2)你也可以使用LINQ。
您需要使用GroupBy方法。
示例和详细信息为here。
我的小提琴:.NET Fiddle
C#代码示例:
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Program
{
public class SomeClass
{
public string Parent { get; set; }
public string Child { get; set; }
}
public static void Main()
{
var datas = new List<SomeClass>
{
new SomeClass{ Parent = "Bob", Child = "Brett" },
new SomeClass{ Parent = "Bob", Child = "Cindy" },
new SomeClass{ Parent = "Bob", Child = "John" },
new SomeClass{ Parent = "Alice", Child = "Pierre" },
new SomeClass{ Parent = "Alice", Child = "John" }
};
var groups = datas.GroupBy(n => n.Parent)
.Select(n => new
{
Parent = n.Key,
Childs = string.Join(",", n.Select(i => i.Child))
})
.ToList();
var result = string.Join("\n", groups);
Console.WriteLine(result);
}
}
答案 1 :(得分:1)
正如您在SQL查询中使用的那样 - 您也可以在Linq中使用GroupBy
。
例如,您有一个接收数据的类,如:
public class ReceivedDataObject
{
public string Parent { get; set; }
public string Child { get; set; }
}
以及包含所有已接收元素的集合,例如
var receivedData = new List<ReceivedDataObject>
{
new ReceivedDataObject { Parent = "Bob", Child = "Brett" },
new ReceivedDataObject { Parent = "Bob", Child = "Cindy" },
new ReceivedDataObject { Parent = "Bob", Child = "John" },
new ReceivedDataObject { Parent = "Alice", Child = "Pierre" },
new ReceivedDataObject { Parent = "Alice", Child = "John" }
};
现在,您可以使用GroupBy
按Parent
属性对收到的对象进行分组。
var groupData = receivedData.GroupBy(rd => rd.Parent);
对于结果的输出,您可以使用
foreach(var group in groupData)
{
Console.WriteLine($"{group.Key}: {string.Join(", ", group.Select(p => p.Child))}");
}
// Output
// Bob: Brett, Cindy, John
// Alice: Pierre, John
或作为新的项目清单:
var result = new List<ReceivedDataObject>();
foreach(var group in groupData)
{
result.Add(new ReceivedDataObject() { Parent = group.Key, Child = string.Join(", ", group.Select(p => p.Child)) } );
}