scott lafoy
scott lafoy

Reputation: 1013

Use Linq to create sub lists grouped by a property

I have a collection of surveys which is a custom class. The surveys contain a property called UWI. I want to create multiple lists for each unique UWI.

A tricky part is, a UWI is a location. It can be written out as 00/01-08-023-23W4/0 The last character of the string (0 in this case) tells you the event underground at which it takes place, and the first part is the surface location. I want to group all of the UWI's by the surface location not taking into account the depth.

For example:

00/01-08-023-23W4/0

and

00/01-08-023-23W4/3

are the same surface location but they have different events, so these should be grouped.

While trying to work through the problem I tried:

 var test =  directionalSurveys.Select(a => a.UWI.Remove(a.UWI.Length - 1, 1));

This just returned a single list of UWI's.

If the main list had 5 objects in its collection:

00/01-08-023-23W4/0

00/01-08-023-23W4/1

00/01-08-023-23W4/2

00/01-06-028-19W4/0

00/01-04-018-15W4/0

The end result would be 3 new lists. The first 3 as a list, the fourth one as a list, and the fifth one as a list.

Upvotes: 0

Views: 264

Answers (1)

Servy
Servy

Reputation: 203802

Use GroupBy to group the items:

var query = directionalSurveys.GroupBy(a => a.UWI.Remove(a.UWI.Length - 1, 1));

Upvotes: 3

Related Questions