Suppose, for example, in my C# code, I have MyClass
, defined as:
public class MyClass
{
public string GroupName;
public DateTime Dt;
public int Id;
public string Val;
.... other properties ....
}
And suppose I had the following List<MyClass>
(showing it as a table since it seems the easiest way to describe the contents):
GroupName: Dt: Id: Val:
Group1 2016/01/01 1 Val1
Group1 2016/01/02 1 Val1
Group1 2016/01/03 1 Val1
Group1 2016/01/04 1 Val2
Group1 2016/01/05 1 Val3
Group1 2016/01/06 1 Val1
Group1 2016/01/07 1 Val1
Group1 2016/01/08 1 Val4
Group1 2016/01/09 1 Val4
With, obviously, the same kind of thing occurring for multiple GroupName
s and different Id
s.
What I would like to get from this list is, for any named group, each first changed value - So the output for Group1
would be:
Dt: Id: Val:
2016/01/01 1 Val1
2016/01/04 1 Val2
2016/01/05 1 Val3
2016/01/06 1 Val1
2016/01/08 1 Val4
In other words, for a given GroupName
:
- Group by Id
- Order by Date
- Select any item within each group where item[index] != item[index-1]
So, I got the following code working:
public IEnumerable<MyClass> GetUpdatedVals(List<MyClass> myVals, string groupName)
{
var filteredVals = myVals.Where(v => v.GroupName == groupName).ToList();
return filteredVals
.OrderBy(v => v.Id)
.ThenBy(v => v.Dt)
.Where((v, idx) => idx == 0 || v.Id != filteredVals[idx - 1].Id || v.Val != filteredVals[idx - 1].Val)
.Select(v => v);
}
But it seems like there should be a better way to do this via Linq using GroupBy or something not having to create a separate holding list.
Any ideas? Or is this a "perfectly good" / the best way?
Thanks!