Search code examples
c#wpfdatagrid

Combining matching values in 2 observablecollections into a 3rd [WPF]


Hello so I have one ObservableCollection that looks like this:

new time { Arrival = stringlist[0], Departure = stringList[1]};
new time2 { Arrived = stringlist[0], Departed = stringList[1]};

I would like to make a new ObservableCollection called datagridTime and insert into this ObservableCollection only records that match so lets say we have

Time `ObservableCollection`

Arrival   |     Departure
---------------------------------
10                 20
10                 30
10                 10
Time2 `ObservableCollection`

Arrival   |     Departure
---------------------------------
10                 20
10                 30
10                 20
datagridTime `ObservableCollection`

Arrived   |     Departed
---------------------------------
10                 20
10                 30

Solution

  • Here is a short sample App which should do what you want.

    The magic part is this:

    public ObservableCollection<Person> People1 { get; } = new ObservableCollection<Person>()
    {
        new Person("Donald", "Duck"),
        new Person("Daisy", "Duck"),
        new Person("Jack", "Daniels")
    };
    
    public ObservableCollection<Person> People2 { get; } = new ObservableCollection<Person>()
    {
        new Person("Donald", "Duck"),
        new Person("Daisy", "Duck"),
        new Person("Jim", "Beam")
    };
    
    public IEnumerable<Person> PeopleInBothCollections
    {
        get
        {
            foreach (var person in People1)
            {
                if (People2.Any(x => x.FirstName == person.FirstName && x.LastName == person.LastName))
                {
                    yield return person;
                }
            }
        }
    }
    

    When ever you raise the PropertyChanged-event it should update your third list: enter image description here

    And here is the link to the example: https://github.com/timunie/MahApps.Metro.Examples/tree/master/src/MahApps.Metro.Examples/IntersectTwoLists