Click here to Skip to main content
11,721,289 members (81,452 online)
Click here to Skip to main content

Tagged as

Grouping based on two or more properties

, 30 Dec 2011 CPOL 9.6K
Rate this:
Please Sign up or sign in to vote.
Custom ICollection View to group items based on two or more properties in same level
Original Blog post can be found here here[^]

By default CollectionViewSource nests groupings when two or more property names are specified as GroupDescriptions. this is an attempt to group items in same level based on two or more property names.

In Short it can be expressed as,

1. Implement ICollectionView
2. Listen for GroupDescription changes,
3. When GroupDescription changed, get possible unique group names, and associated items.
4. Create CollectionViewGroup from the above combination.
5. Bind this as the item source.

void OnGroupDescriptionsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
    groups.Clear();
 
    var propNames = GroupDescriptions
        .OfType<PropertyGroupDescription>()
        .Select(pDesc => pDesc.PropertyName);
 
    var groupNames = SourceCollection
        .OfType<object>()
        .Select(i => GetGroupName(i,propNames))
        .Distinct();
 
    var viewGroups = groupNames
        .Select(gName => new CollectionViewGroup(gName,
            SourceCollection
            .OfType<object>()
            .Where(i => GetGroupName(i, propNames).Equals(gName))));
 
    foreach (object group in viewGroups)
        groups.Add(group);
}
 
private string GetGroupName(object item, IEnumerable propNames)
{
 
        var groupName = string.Empty;
 
	foreach (string propertyName in propNames)
	{
		groupName += item.GetType()
		.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public)
			.GetValue(item, null)
			.ToString() + " ";
	}
 
        return groupName;
}

Here is the Sample[^] Check it out and let me know your suggestions!!!

HaPpY Coding!!! Smile | :)

License

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

Share

About the Author

VallarasuS
Software Developer
India India
I code, learn, listen, and some day in a near future be a proud farmer.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150901.1 | Last Updated 30 Dec 2011
Article Copyright 2011 by VallarasuS
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid