Wednesday, September 19, 2018

c# - How can I sort a list of objects by a member of each object?




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 candleList = new List();


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


Answer



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 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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...