在VB.NET中通过LINQ对通用列表进行分组 [英] Grouping a generic list via LINQ in VB.NET
问题描述
我需要收集一个集合并通过Linq对其进行分组,但是我所看到的所有示例都以某种方式或其他方式失败,但语法上有些差异,我不太喜欢.
I need to take a collection and group it via Linq but all the examples I've seen fail in some manner or other with some syntax difference that I can't quite lick.
我的收藏集:
Dim a As New List(Of ProcessAlert)
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Alert", 2))
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Document", 2))
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Note", 2))
a.Add(New ProcessAlert("0000112367", "jdoe@home.com", "Alert", 1))
a.Add(New ProcessAlert("0000112367", "jdoe@home.com", "Document", 1))
a.Add(New ProcessAlert("0000112367", "jdoe@home.com", "Note", 1))
Return a
我需要将这个收藏集变成一种简单的方法来获得最终结果:
I need to turn this collection into a simple way to give this final outcome:
"5551110000@txt.att.net", "Alert, Document, Note"
"jdoe@home.com", "Alert, Document, Note"
这是ProcessAlert
类的定义:
Public Class ProcessAlert
Public LoanNumber As String
Public EmailAddress As String
Public AlertType As String
Public AlertMethodID As Byte
End Class
预先感谢
CD
我设法转换为VB:
Dim res = Alerts.GroupBy(Function(i) i.EmailAddress).Select(Function(g) New KeyValuePair(Of String, String)(g.Key, String.Join(",", g.Select(Function(x) x.AlertType).ToArray())))
现在如何将LoanNumber和电子邮件地址添加到组中,这样我的结果是: "0000112367","jdoe@home.com",警报,文档,注释"
Now how do I add in to group by LoanNumber and Email Address so that my result is: "0000112367","jdoe@home.com", "Alert, Document, Note"
推荐答案
这是我要编写的linq代码(在C#中-很抱歉,我无法在VB中完成它)
Here is the linq code I would write (in c# - sorry I couldn't complete it in VB)
var res = a.GroupBy(i=>i.EmailAddress )
.Select(g=> new KeyValuePair<string, string>(
g.Key,
string.Join(",", g.Select(x=> x.AlertType ).ToArray())
));
这将在KeyValuePair集合中为您提供所需的输出
This will give you the output you want in a collection of KeyValuePair
为了将它们分别按LoadNumber和EmailAddress进行分组,这将是c#代码:
in order to group them by both LoadNumber and EmailAddress this would be the c# code:
var res = alerts
.GroupBy(a => new { L = a.LoanNumber, E = a.EmailAddress })
.Select(a => new
{
LoadNumber = a.Key.L,
EmailAddress = a.Key.E,
Types = string.Join(", ", a.Select(x => x.AlertType).ToArray())
}).ToList();
其中的结果是Complext类型{LoadNumber,EmailAddress,类型}的列表
where result is a List of a Complext type {LoadNumber, EmailAddress, Types}
这篇关于在VB.NET中通过LINQ对通用列表进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!