Click here to Skip to main content
15,895,822 members
Articles / Desktop Programming / WPF
Tip/Trick

Grouping based on two or more properties

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
30 Dec 2011CPOL 15K  
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
I code, learn, read and listen.

Comments and Discussions

 
-- There are no messages in this forum --