LINQ - 选择具有特定日期的元素

时间:2016-03-21 06:21:12

标签: c# .net linq

我有一个类,其中一个属性为DateTime。

public class ClassWithDate
{
   public int somevalue {get;set;}
   public DateTime somedate {get;set;}
}

我有另一个字符串列表,其中包含日期(星期一,星期二等)的值

List<string> someDays;

我有一个ClassWithDate的IEnumerable列表

IEnumerable<ClassWithDate> classWithDates;

我希望从classWithDates中选择那些元素,其中date属性不是someDays字符串列表中的一天

这样的事情:

classWithDates.someDate.DayOfWeek != someDays

我知道语法错误,但只是想提供一个例子。

4 个答案:

答案 0 :(得分:1)

你可以这样做。

var results = classWithDates.Where(wd=>!someDays.Contains(wd.somedate.DayOfWeek.ToString()));

var results = classWithDates.Where(wd=>!someDays.Any(s=> sq.Equals(wd.somedate.DayOfWeek.ToString(), StringComparison.OrdinalIgnoreCase)));

工作Example

答案 1 :(得分:1)

List<string> days = new List<string>() { "Monday", "Tuesday", "Friday" };成为工作日的定义列表;和classWithDates是你的收藏;然后以下查询将帮助您完成任务:

var selectedDates = classWithDates.Where(x => !days.Contains(x.somedate.DayOfWeek.ToString()));

这里有一个例子:

 DateTime d = DateTime.Now;
 List<ClassWithDate> classWithDates = new List<ClassWithDate>();
 classWithDates.Add(new ClassWithDate() { somedate = d.AddDays(1), somevalue = 12 });
 classWithDates.Add(new ClassWithDate() { somedate = d.AddDays(2), somevalue = 12 });
 classWithDates.Add(new ClassWithDate() { somedate = d.AddDays(3), somevalue = 12 });
 classWithDates.Add(new ClassWithDate() { somedate = d.AddDays(4), somevalue = 12 });
 classWithDates.Add(new ClassWithDate() { somedate = d.AddDays(5), somevalue = 12 });
 classWithDates.Add(new ClassWithDate() { somedate = d.AddDays(6), somevalue = 12 });
 List<string> days = new List<string>() { "Monday", "Tuesday", "Friday" };
 var selectedDates = classWithDates.Where(x => !days.Contains(x.somedate.DayOfWeek.ToString()));

答案 2 :(得分:1)

试试这个

 List<ClassWithDate> _sampleList=new List<ClassWithDate>(); 
_sampleList.Add(new ClassWithDate(){somevalue=10,somedate=new DateTime(1980, 5, 5)});
_sampleList.Add(new ClassWithDate(){somevalue=10,somedate=new DateTime(1982, 10, 20)});
_sampleList.Add(new ClassWithDate(){somevalue=10,somedate=new DateTime(1984, 1, 4)});
_sampleList.Add(new ClassWithDate(){somevalue=10,somedate=new DateTime(1979, 6, 19)});



List<string> daysList = new List<string>() { "Monday", "Tuesday" };
IEnumerable<ClassWithDate> selectedDates = _sampleList.Where(x => !daysList.Contains(x.somedate.ToString("dddd")));

foreach(ClassWithDate cl in selectedDates)
{
  Console.WriteLine(cl.somedate.ToString("dddd"));      
}

答案 3 :(得分:1)

这样的事情:

  // Let be comparison case insensitive
  HashSet<String> hs = new HashSet(someDays, StringComparer.OrdinalIgnoreCase);

  // providing that classWithDates doesn´t contain null items
  var result = classWithDates
    .Where(item => !hs.Contains(item.somedate.DayOfWeek.ToString()));