我有一个这样的列表
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>
我想获取列表中所有不同的月份。我试过这样做
List<string> monthNamesList = eventListResponse.result.Select(s => Convert.ToDateTime(s.startDate).ToString("MMMM")).Distinct().ToList();
它完成了任务,唯一的问题是如果列表包含两个元素
2014-03-31T12:30:03
2013-03-31T12:30:03
我的代码将只返回一个月,在那里我想得到它像2014 March
和2013 March
。所以我创建了一个新的模型类,带有年和月
public class MonthYearMOdel
{
public string month;
public string year;
}
有谁能指出我如何从我的第一个列表中获取不同的月份并存储在List<MonthYearMOdel>
中。其中2014 March
和2013 March
均存储
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();
简单的方法(每个字符串包含月份和年份):
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();