1

I have two ILists in my which are getting values from the separate tables within the database. These tables contain the same columns and values but for other reasons the client needs them stored in separate tables.

private IList<MeterReadingDto> _meterReadings;
private IList<PseudoReadingDto>  _pseudoReading;
public IList<MeterReadingDto> MeterReadings
    {
        get
        {
            return _meterReadings != null ? _meterReadings.OrderByDescending(x => x.ReadDate).ToList() : null;
        }
        set { _meterReadings = value; }
    }

    public IList<PseudoReadingDto> PseudoReadings
    {
        get
        {
            return _pseudoReading != null ? _pseudoReading.OrderByDescending(x => x.ReadDate).ToList() : null;
        }
        set { _pseudoReading = value; }
    }

As you can see they both get the results and store them, but i now need to merge/union these list so that they can be displayed in one table. Any ideas on how to do this

Blahwoo
  • 69
  • 2
  • 10
  • So why do you use two different classes for the same data structure from two tables? – Viktor Kireev Apr 30 '15 at 15:55
  • Note that if they have the same columns, you will want them to implement a common interface to simplify merging with Concat, or have them share a common base class. – Eric J. Apr 30 '15 at 15:59

3 Answers3

2

Well, if you can extract an interface (or ever a base class) for MeterReadingDto and PseudoReadingDto, than you could merge them to a IEnumerable or IList of that.

i.e.

public IEnumerable<BaseReadingDto> AllReadings {
  get{
    return MeterReadings.Concat(PseudoReadings);
  }
}
SWeko
  • 30,434
  • 10
  • 71
  • 106
0

Consider using the IEnumerable method extension Union.

NOTE: Using this operation will result in duplicate elements between the two collections being removed from the result.

Scott Nimrod
  • 11,206
  • 11
  • 54
  • 118
  • Union will discard any elements that the two IList have in common. – Eric J. Apr 30 '15 at 15:56
  • 1
    Oh, okay. I saw this note: The Concat method differs from the Union method because the Concat method returns all the elements in the input sequences including duplicates, whereas Union returns only unique values. Thanks for clarifying. – Scott Nimrod Apr 30 '15 at 16:00
0

You need to be able to treat both PseudoReadingDto and MeterReadingDto as the same object type. You could look into anonymous types, but I suggest having both implement the same interface (like maybe IReadingDto). Then you can create a new List<IReadingDto> and combine the lists.

If they share the same type, you can use List.AddRange() to append the lists together.

ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
  • Using AddRange is especially efficient compared to Concat if you know the size of the final list ahead of time http://stackoverflow.com/a/4488073/141172. – Eric J. Apr 30 '15 at 16:04