Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Any easy way to split a list into multiple lists based on a property of the objects?
Posted
Comments
Andreas Gieriet 11-Dec-14 18:44pm    
Any sample code where you struggle?
Andi

How about using LINQ to object?
C#
List<...> initialList = ...;
List<...> listBasedOnPredicateA = initialList.Where(item => predicateA(item)).ToList();
List<...> listBasedOnPredicateB = initialList.Where(item => predicateB(item)).ToList();
...

The predicates are either functions that evaluate some item's properties and return true/false, or you do a direct access to the properties, e.g. item.PropA == ValueA, etc.

[EDIT]
Based on the comments below: You might also do the grouping approach:
C#
List<ItemType> initialList = ...;
List<List<ItemType>> listOfList = initialList.GroupBy(item => item.Property)
                                             .Select(group => group.Tolist())
                                             .ToList();
[/EDIT]

Cheers
Andi
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 11-Dec-14 19:00pm    
Basically, that's right, but I voted 4. Here is a little problem with that:
Additionally, as required operation is split, it takes not just creation of new lists referencing same objects, but all objects added to a new list should be removed from an old one.
Note that otherwise your algorithm may cause double references, because some items may meed predicate A and B at the same time, so this is certainly not split.
—SA
Andreas Gieriet 11-Dec-14 19:19pm    
Hello Sergey,
Thanks for your 4.
Given the fuzzy question I regarded "splitting" in a broader sense. I regard it the responsibility of the OP to make meaningful predicates. He has a tool at hand to do it, at least ;-).
If it's about exclusive selection, then you might go a "bin" approach: the selecting function will put the items into something like Dictionary<TKey, List<TValue>>. This looks generic but a bit over-engineered to me. Some responsibility is in the programmers hand...
Or you have a factory for the predicates that makes sure that only exclusive where clauses are produced... ;-)
Cheers
Andi
Sergey Alexandrovich Kryukov 11-Dec-14 21:10pm    
Agree... And the note by Philippe Mori below is also adequate: this is rather grouping by. Splitting also wouldn't be a big problem. :-)
Cheers,
—SA
Andreas Gieriet 12-Dec-14 11:21am    
So, I updated the solution.
Cheers
Andi
Sergey Alexandrovich Kryukov 12-Dec-14 12:04pm    
Very good; 5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900