开发者

Grouping a generic list via LINQ in VB.NET

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.

My collection:

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 ProcessAl开发者_运维知识库ert("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"

Here's the definition of the ProcessAlert class:

Public Class ProcessAlert
  Public LoanNumber As String
  Public EmailAddress As String
  Public AlertType As String
  Public AlertMethodID As Byte
End Class

Thanks in advance,

CD

I've managed to convert to 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())))

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"


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

This will give you the output you want in a collection of KeyValuePair

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

where result is a List of a Complext type {LoadNumber, EmailAddress, Types}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜