简体   繁体   中英

Foreach group items from a list of objects

I need to group a big list of elements according to a certain atribute. Is it possible in C# to do a foreach with a 'where' clause in a list of objects or is there a better way? For example, I have 5000 records and 3 groups that separate them.

Foreach list.item where item.group = group1{
do action one for every record from group1
}

and so on... ps.: I already have the records at this point of code so I don't think Linq would help.

You can separate a larger list into smaller ones, based on a property, by using ToLookup . The ToLookup method will produce a dictionary of lists, where the key is the property value that you are separating them by and the list contains all of the elements that match.

For example, if your objects have a CategoryID you can separate them into a dictionary of lists like this:

var smallLists = bigList.ToLookup( item => item.CategoryID, item => item );

You can then iterate them like this:

foreach (var bucket in smallLists)
{
    Console.WriteLine("Bucket:");
    foreach (var item in bucket)
    {
        Console.WriteLine("Item {0} with category {1}", item.Name, item.CategoryID);
    }
}

See a working example on DotNetFiddle .

This basic template should do what you need. You can also use a dictionary to map the groups to.

using System.Linq; 

class Program
{
    class Item
    {
        public int Key { get; set; }
        public string Name { get; set; }
    }

    static void Main(string[] args)
    {
        var actions = new Dictionary<int, Action<Item>> {
            { 1, Action1 },
            { 2, Action2 },
            { 3, Action3 }
        };

        var items = new List<Item>();

        foreach (var group in items.GroupBy(x => x.Key))
        {
            var action = actions[group.Key];
            foreach (var item in group)
            {
                action(item);
            }
        }
    }

    static void Action1(Item item)
    {

    }

    static void Action2(Item item)
    {

    }

    static void Action3(Item item)
    {

    }
}

I think that you want to do is to group items of list by a Group and then create another list with each group and his items.

If that is the case, you can do something like this:

var grouped = items/*.Where(c => c.group == //desired group if want's to filter//)*/
     .GroupBy(c => c.group);
var results = grouped.Select(c => new {
     Group = c.Key.group,
     Items = c.Select(c => new { c.PropertyOfItem1, c.PropertyOfItem2, // etc // })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM