2
class candle
{
    public DateTime date { get; set; }
    public double open { get; set; }
    public double high { get; set; }
    public double low { get; set; }
    public double close { get; set; }     
}
List<candle> candleList = new List<candle>();

Assuming I have added many candles to candeList, How can I then sort candleList by date?

Also, how can I remove all duplicate entries from candleList?

Thank you

stormist
  • 5,709
  • 12
  • 46
  • 65

3 Answers3

4

Pretty standard, simple linq.

var candleList = candleList.Distinct().OrderBy(x => x.date).ToList();

As Adam mentioned below, this will only remove duplicate instances within the list, not instances which all of the same property values.

You can implement your own IEqualityComparer<Candle> as an option to get passed this. IEqualityComparer

You may want to take a look at msdn, and read up on Linq and Enumerable Methods: MSDN - Enumerable Methods

Khan
  • 17,904
  • 5
  • 47
  • 59
  • 4
    `Distinct` on a class would just do reference equality, not anything with the property values. Also, that sort is not in-place, it produces an `IEnumerable`. – Adam Houldsworth Sep 23 '13 at 13:36
  • 1
    @AdamHouldsworth, your point is extremely valid and relevant. But it does not make my answer incorrect (that's to the downvoter). I have provided more information. – Khan Sep 23 '13 at 13:43
  • 1
    I noticed, and I'm not the downvoter. – Adam Houldsworth Sep 23 '13 at 13:44
1

How can I then sort candleList by date?

var orderedList = candleList.OrderBy(p=>p.date);

Also, how can I remove all duplicate entries from candleList?

You should tell us how you compare two candle objects. Assuming by date you can do:

var uniqueList = candleList.GroupBy(p=>p.date).Where(p=>p.Count() == 1).ToList();

Also, you can use Distinct() or intorduce a IEqualityComparer<candle> to this method to compare two candle objects and remove the duplicates.

Alireza
  • 10,237
  • 6
  • 43
  • 59
1

if you're using .NET 3.5 and above, you can use the OrderBy extension over IList like so:

var orderList = candleList.OrderBy(s => s.date);

Alternative you can use the SortBy

var orderList = candleList.SortBy((x, y) => x.date.CompareTo(y.date) );

To remove the duplicates you can do:

var distinctList = orderList.GroupBy(x => x.date).Select(grp => grp.First());

Finally to get the list again do

var finalList = distinctList.ToList();

In fluent way:

List<candle> finalList = candleList.OrderBy(s => s.date).Distinct().ToList();

By the way there quite a few other questions in stackoverflow that explains each of this questions, search them and you'll find other details.

saamorim
  • 3,855
  • 17
  • 22