Union two ObservableCollection Lists

前端 未结 2 1159
别跟我提以往
别跟我提以往 2021-02-08 16:31

I have two ObservableCollection lists, that i want to unite. My naive approach was to use the Union - Method:

ObservableCollection unitedPoints = ob         


        
相关标签:
2条回答
  • 2021-02-08 17:29

    The LINQ Union extension method returns an IEnumerable. You will need to enumerate and add each item to the result collection:-

    var unitedPoints = new ObservableCollection<Point> ();
    foreach (var p in observableCollection1.Union(observableCollection2))
       unitedPoints.Add(p);
    

    If you'd like a ToObservableCollection then you can do:

    public static class MyEnumerable
    {
        public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
        {
            var result = new ObservableCollection<T> ();
            foreach (var item in source)
               result.Add(item);
            return result;
        }
     }
    

    Now your line is:

    var unitedPoints = observableCollection1.Union(observableCollection2).ToObservableCollection();
    
    0 讨论(0)
  • 2021-02-08 17:31

    Do you want to merge the existing contents, but then basically have independent lists? If so, that's relatively easy:

    ObservableCollection<Point> unitedPoints = new ObservableCollection<Point>
        (observableCollection1.Union(observableCollection2).ToList());
    

    However, if you want one observable collection which is effectively a "view" on others, I'm not sure the best way to do that...

    0 讨论(0)
提交回复
热议问题