C# 从列表中获取月份名称和年份
我试图使用LINQ从一个有2个属性的列表中检索月份名称和年份,而不重复月份和年份的名称C# 从列表中获取月份名称和年份,c#,entity-framework,linq,c#-4.0,C#,Entity Framework,Linq,C# 4.0,我试图使用LINQ从一个有2个属性的列表中检索月份名称和年份,而不重复月份和年份的名称 public class Record { public int Id { get; set; } public DateTime Date { get; set; } } DateTime d1 = new DateTime(2015, 1, 14); DateTime d2 = new DateTime(2016, 3, 12); DateTime d3 = new DateTime(2
public class Record
{
public int Id { get; set; }
public DateTime Date { get; set; }
}
DateTime d1 = new DateTime(2015, 1, 14);
DateTime d2 = new DateTime(2016, 3, 12);
DateTime d3 = new DateTime(2016, 4, 17);
DateTime d4 = new DateTime(2015, 5, 19);
DateTime d5 = new DateTime(2016, 6, 10);
List<Record> dates = new List<Record>
{
new Record { Id= 1, Date = d1 },
new Record { Id= 2, Date = d2 },
new Record { Id= 3, Date = d3 },
new Record { Id= 4, Date = d4 },
new Record { Id= 5, Date = d5 }
};
//Month should be in string format (January,June, etc)
// Get Year and Months from that list withour repeating the names
//List<string> months =
//List < string > years =
公共类记录
{
公共int Id{get;set;}
公共日期时间日期{get;set;}
}
DateTime d1=新的日期时间(2015,1,14);
DateTime d2=新的日期时间(2016,3,12);
DateTime d3=新的日期时间(2016,4,17);
DateTime d4=新的日期时间(2015,5,19);
DateTime d5=新的日期时间(2016,6,10);
列表日期=新列表
{
新记录{Id=1,Date=d1},
新记录{Id=2,Date=d2},
新记录{Id=3,Date=d3},
新记录{Id=4,Date=d4},
新记录{Id=5,Date=d5}
};
//月份应为字符串格式(一月、六月等)
//用我们重复的名字从列表中获得年份和月份
//列出月份=
//列出年=
使用扩展方法简化(摘自):
您可以这样做:
var months = dates.Select(r => r.Date.ToMonthName())
.Distinct();
var years = dates.Select(r => r.Date.Year)
.Distinct();
请注意,我在这里将年份指定为
int
,如果您想要字符串,那么只需添加ToString()
,并使用扩展方法简化它(取自):
您可以这样做:
var months = dates.Select(r => r.Date.ToMonthName())
.Distinct();
var years = dates.Select(r => r.Date.Year)
.Distinct();
请注意,我在这里将年份指定为
int
,如果需要字符串,只需添加ToString()
几个月,并使用Linq:
List<string> months = dates.Select(d => d.Date.ToString("MMMM"))
.Distinct()
.ToArray();
虽然还不清楚你想要的年份列表是什么样子的
有关
Distinct
的信息,请访问并使用Linq查看数月:
List<string> months = dates.Select(d => d.Date.ToString("MMMM"))
.Distinct()
.ToArray();
虽然还不清楚你想要的年份列表是什么样子的
有关Distinct
的信息,请访问