views:

45

answers:

1

I have List object filled with instances of a custom struct.

        list.Add(new Mail("mail1", "test11", "path11"));
        list.Add(new Mail("mail2", "test12", "path12"));
        list.Add(new Mail("mail1", "test13", "path13"));
        list.Add(new Mail("mail1", "test14", "path14"));
        list.Add(new Mail("mail2", "test15", "path15"));

        var q = from x in list
                group x by x.Sender into g
                let count = g.Count()
                where count > 2
                orderby count descending
                select new { Sender = g.Key};

        foreach (var x in q)
        {
            Console.WriteLine(x.Sender);
        }

The output of that code would be this:

mail1

But since I need to work on every Mail item which is available more than twice (or maybe n-times) based on the value of a certain property (i.e. Sender), I need a query to show me ALL items that occur more often than n (including a reference to the corresponding Mail item.

After filling the query I would love to do something like this:

    foreach (var x in q)
    {
        Console.WriteLine(x.Sender + " - " + x.Path + " - " + x.Count);
    }

I'm new to LINQ but I'm sure this is somehow possible.

Thanks for your help

Regards, Kevin

+1  A: 

Include the properties to be added to your anonymous type.

var q = from x in list
        group x by x.Sender into g
        let count = g.Count()
        where count > 2
        orderby count descending
        select new
        {   // add your fields here
            Sender = g.Key,
            Path = ...,      // not sure what you wanted here
            Count = count,
            Mails = g,       // include the mails in the group
        };

Then you can do with it what you want.

foreach (var x in q)
{
    // each x is a type with the fields
    //     Sender
    //     Path
    //     Count
    //     Mails
    Console.WriteLine(x.Sender + " - " + x.Path + " - " + x.Count);
    foreach (var mail in x.Mails)
    {
        // do something with each individual mail
    }
}
Jeff M
Thats perfect, though I don't "like" nested for(each)-loops ;-) Anyway, thanks a lot
jarod1701