Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Grouping based on two or more properties

0.00/5 (No votes)
30 Dec 2011 1  
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.

C#
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!!! :)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here