1

I am generating two lists which will contain the same number and order of objects, but the will have different property values since the second list is an updated version of the data.

I need to reconsile both lists into one, taking some data from the old list and some from the new. IEnumerable.Zip seems perfect for this task, except that under certain conditions when comparing the two objects, I will want the resultSelector function to return two objects.

Is this possible or does anyone know of a workaround?

4
  • 1
    Zip doesn't do what you want at all. It combines two sequences pairwise only without checking any conditions or if the elements match. Sounds like you need Join instead Dec 15, 2020 at 10:42
  • 1
    @PanagiotisKanavos: The OP said it contains the same number and order of objects, so it sounds like Zip is fine.
    – Jon Skeet
    Dec 15, 2020 at 10:53
  • Zip can't emit multiple records per pair though Dec 15, 2020 at 10:54
  • 1
    @PanagiotisKanavos: Not on its own, no - but it doesn't need to. It's got one job, which is to zip the pairs together. Then SelectMany is the normal way of handling the "convert one item into potentially-multiple" items - see my answer.
    – Jon Skeet
    Dec 15, 2020 at 10:57

1 Answer 1

2

It sounds like you need to combine Zip and SelectMany:

// Assuming .NET Core 3.0 or later; in other versions you'd need to provide
// a selector to the Zip method, which would just return the tuple.
var result = first.Zip(second)
                  .SelectMany(tuple =>
                  {
                      // Deconstruct the tuple into the two elements
                      var (x, y) = tuple;
                      // Yield two items case
                      if (x.Id != y.Id)
                      {
                          yield return x;
                          yield return y;
                      }
                      else
                      // Yield one item case
                      {
                          yield return x;
                      }
                  });

(You may well want to extract that logic into a separate method, of course. We can't give a more concrete example to suit your situation as the question doesn't give a concrete example of what you're doing.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.