How to group consecutive similar items of a collection?

后端 未结 5 858
忘了有多久
忘了有多久 2020-12-06 23:06

Consider the following collection.

  • True
  • False
  • False
  • False
  • True
  • True
  • False
  • False

I

5条回答
  •  萌比男神i
    2020-12-06 23:24

    public class GroupConsecutiveEqualItemsConverter : IValueConverter
    {
        static readonly object UnsetValue = new object();
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            IEnumerable source = value as IEnumerable;
            if (source == null) return DependencyProperty.UnsetValue;
            string propertyName = parameter as string;
            var result = new ObservableCollection>();
    
            var notify = value as INotifyCollectionChanged;
            if (notify != null) notify.CollectionChanged += delegate { Reload(result, source, propertyName); };
    
            Reload(result, source, propertyName);
            return result;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    
        void Reload(ObservableCollection> result, IEnumerable source, string propertyName)
        {
            result.Clear();
            object previous = UnsetValue;
            List group = null;
            foreach (object i in source)
            {
                object current = UnsetValue;
                if (propertyName == null)
                {
                    current = i;
                }
                else
                {
                    try
                    {
                        var property = i.GetType().GetProperty(propertyName);
                        if (property != null) current = property.GetValue(i, null);
                    }
                    catch (AmbiguousMatchException) { }
                }
                if (!object.Equals(previous, current))
                {
                    if (group != null) result.Add(group);
                    group = new List();
                }
                group.Add(i);
                previous = current;
            }
            if (group != null && group.Count > 0) result.Add(group);
        }
    }
    
        

    提交回复
    热议问题