Reputation: 5670
I have list like this
public class Result
{
public string id { get; set; }
public string name { get; set; }
public string startDate { get; set; } //smaple date 2014-03-31T12:30:03
}
List<Result>
I want to fetch all distinct month comes inside this list . I have tried something like this
List<string> monthNamesList = eventListResponse.result.Select(s => Convert.ToDateTime(s.startDate).ToString("MMMM")).Distinct().ToList();
And it does the job, Only Problem is that if the list comtains two elements
2014-03-31T12:30:03
2013-03-31T12:30:03
My code will return only one month, where I want to get it like 2014 March
and 2013 March
.
So I created a new model class with year and month
public class MonthYearMOdel
{
public string month;
public string year;
}
Can any one point out how I can fetch distinct months from my first list and store in List<MonthYearMOdel>
.
Where 2014 March
and 2013 March
both will be stored.
Upvotes: 0
Views: 728
Reputation: 2083
try this :
List<MonthYearMOdel> monthNamesList = eventListResponse.result.Select(s => new
{
M = Convert.ToDateTime(s.startDate).ToString("MMMM"),
Y = Convert.ToDateTime(s.startDate).ToString("yyyy")
})
.Distinct()
.Select(u => new MonthYearMOdel()
{
month = u.M,
year = u.Y,
})
.ToList();
Upvotes: 1
Reputation: 672
Simple way (each string contains month and year):
List<string> monthNamesList = eventListResponse.result.Select(s => Convert.ToDateTime(s.startDate).ToString("yyyy MMMM")).Distinct().ToList();
With MonthYearModel
:
public class MonthYearModel
{
public string month;
public string year;
public MonthYearModel(string dateTime)
{
var date = Convert.ToDateTime(dateTime);
this.month = date.ToString("MMMM");
this.year = date.ToString("yyyy");
}
public bool Equals(object arg)
{
var model = arg as MonthYearModel;
return (model != null) && model.month == this.month && model.year == this.year;
}
public int GetHashCode()
{
return (month.GetHashCode() * 397) ^ year.GetHashCode();
}
}
List<MonthYearModel> = eventListResponse.result.Select(s => new MonthYearModel(s.startDate)).Distinct().ToList();
Upvotes: 1