在VB.NET中通过LINQ对通用列表进行分组

时间:2011-06-26 23:36:32

标签: vb.net linq

我需要收集一个集合并通过Linq对其进行分组,但是我看到的所有示例都以某种方式或其他方式失败,并且有一些语法差异,我无法舔它。

我的收藏:

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

我需要将这个集合变成一个简单的方法来提供最终结果:

"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”,“警报,文件,注意”

1 个答案:

答案 0 :(得分:4)

这是我要写的linq代码(在c#中 - 抱歉我无法在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

集合中所需的输出

为了通过LoadNumber和EmailAddress对它们进行分组,这将是c#代码:

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();

其中result是Complext类型的列表{LoadNumber,EmailAddress,Types}