c#列表项如果存在于数组中则不添加

时间:2014-10-04 19:25:48

标签: c# linq

我有一些天(mon,tue等等),我可能不想展示,所以当我创建一个日期列表时,如果它们已经在" hiddendays",它没有添加它们。

// This would return for example 1, 2
var hDays = account.ScheduleHiddenDays.Split(',').Select(int.Parse).ToList();

var daySunday = new ViewModels.Day()
{
   Id = 0,
   Name = "Sunday"
};
var dayMonday = new ViewModels.Day()
{
   Id = 1,
   Name = "Monday"
};
var dayTuesday = new ViewModels.Day()
{
   Id = 2,
   Name = "Tueday"
};
var dayWednesday = new ViewModels.Day()
{
   Id = 3,
   Name = "Wednesday"
};
var dayThursday = new ViewModels.Day()
{
   Id = 4,
   Name = "Thursday"
};
var dayFriday = new ViewModels.Day()
{
 Id = 5,
 Name = "Friday"
};
var daySaturday = new ViewModels.Day()
{
 Id = 6,
 Name = "Saturday"
};

// This is where I need to check if they exist in hDays, it doesn't add them to this list. But how?
model.ScheduleHiddenDays = new List<ViewModels.Day>()
{
   daySunday,
   dayMonday,
   dayTuesday,
   dayWednesday,
   dayThursday,
   dayFriday,
   daySaturday
};

1 个答案:

答案 0 :(得分:4)

有些事情如下:

var days = new List<ViewModels.Day>()
{
 daySunday,
 dayMonday,
 dayTuesday,
 dayWednesday,
 dayThursday,
 dayFriday,
 daySaturday
};

model.ScheduleHiddenDays = days.Where(x => !hDays.Contains(x.Id)).ToList();