2

I have a problem trying to figure out a LINQ query for the following.

The columns are MeterSerialNumber, Date, DeviceType (M or C), and then 48 reading value columns.

Some meters will have a corrector fitted. For these meters there will be both an M (DeviceType) row and a C row for the same date. I need just the C rows for these meters.

e.g.

I need a query to convert this:

MeterSerialNumber,Date,DeviceType,Reading1,Reading2,etc
8017680S,19/08/2010,M,12,23,etc 
4504761S,19/08/2010,M,12,23,etc
4504761S,19/08/2010,C,12,23,etc
08000963,19/08/2010,M,12,23,etc

To this:

MeterSerialNumber,Date,DeviceType,Reading1,Reading2,etc
8017680S,19/08/2010,M,12,23,etc
4504761S,19/08/2010,C,12,23,etc
08000963,19/08/2010,M,12,23,etc

I suspect I might need nested queries but just can't get my head round it!

3
  • do you have this as data structures or is it just in a CSV text file? Commented Sep 24, 2010 at 11:53
  • Hi Isak, I have it in objects with field names as above Commented Sep 24, 2010 at 12:05
  • Possible duplicate of LINQ Conditional Group Commented May 23, 2018 at 14:05

2 Answers 2

1

Or try this:

  var group = meters
    .Where(m => m.DeviceType == "M" && !meters.Any(m2 => m2.MeterSerialNumber == m.MeterSerialNumber && m2.DeviceType == "C"))
    .Union(meters
      .Where(m => m.DeviceType == "C" && meters.Any(m2 => m2.MeterSerialNumber == m.MeterSerialNumber && m2.DeviceType == "M")));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks so much for this. It passes the tests perfectly! Now to figure out how it works...
I actually had to add another check for the date. But I now understand it. Again - thanks a lot
1
var query = sourceData.GroupBy(
                x => new { x.MeterSerialNumber, x.Date },
                (k, g) => g.OrderBy(x => x.DeviceType == 'C' ? 0 : 1).First());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.