2

I have a C# list in which there are several columns and rows of data and I am trying to retrieve few of the rows by applying distinct on one column of the list.

For example I have the following data in a C# list AxiomSubSet of type AxiomDS

Month   Strk    Strg    Price   Amount
15-May  3.80    Put     0.0410  200
15-Apr  3.80    Put     0.0410  200
15-Mar  3.80    Put     0.0410  200
15-May  4.20    Put     0.0380  100
15-Apr  4.20    Put     0.0380  100
15-Mar  4.20    Put     0.0380  100
15-May  4.25    Call    0.0620  60
15-Apr  4.25    Call    0.0620  60
15-Mar  4.25    Call    0.0620  60

When I apply a method to above list it should the first row for each distinct Strk like

Month   Strk    Strg    Price   Amount
15-May  3.80    Put     0.0410  200
15-May  4.20    Put     0.0380  100
15-May  4.25    Call    0.0620  60

and store the above data in a temporary list of same type

I tried something like

List<AxiomDS> listTempStrikes = new List<AxiomDS>();
listTempStrikes = AxiomSubSet.Select(x => x.strike).Distinct().ToList());

but not working for obvious reasons. May I know a better way to deal with this?

DoIt
  • 3,270
  • 9
  • 51
  • 103

1 Answers1

2

You need GroupBy

listTempStrikes = AxiomSubSet.GroupBy(x => x.Strk).Select(g => g.First()).ToList();

You can also use the DistinctBy method from the MoreLINQ library

listTempStrikes = AxiomSubSet.DistinctBy(x => x.Strk).ToList();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184