[英]C# LINQ How to find matching item from one list in another list and check for the property in the other list
[英]Linq: add objects from one list to another with an other type, (MVC, C#)
我有一個“ FindItemsResults <Appointment>
列表”,其中包含約會對象。
我想從此列表中選擇“開始”屬性值以及所有約會對象,並將這些值保存在DateTime類型的另一個列表中…… List<DateTime> avaliableBookingDays
List<DateTime> avaliableBookingDays = new List<DateTime>();
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
IEnumerable<DateTime> res = from x in appointments
select new DateTime { (x.Start};
avaliableBookingDays.AddRange(res);
我的LINQ表達式失敗:
IEnumerable<DateTime> res = from x in appointments
select new DateTime { (x.Start};
我收到這樣的錯誤:
無法使用集合初始化器初始化類型“ DateTime”,因為它沒有實現“ System.Collections.IEnumerable”
上述LINQ必須做到這一點:
foreach (var appObj in appointments)
{
avaliableBookingDays.Add(appObj.Start);
}
如果Enumerable.Select
順序將項目投影為其他類型,請使用Enumerable.Select
:
var avaliableBookingDays = appointments.Select(a => a.Start).ToList();
請注意,查詢語法中沒有等效的ToList()
運算符。 因此,最好的辦法是獲取IEnumerable<DateTime>
結果並將其轉換為以后的列表:
IEnumerable<DateTime> res = from x in appointments
select x.Start;
var avaliableBookingDays = res.ToList();
另外請記住DateTime
是一個值類型 。 您無需創建此類型的新實例即可獲取約會開始時間的副本-副本將自動創建。
您的代碼甚至都不會編譯
IEnumerable<DateTime> res = from x in appointments
select new DateTime { (x.Start};
因為它有語法錯誤! 在您選擇的部分中,您將投影到一個新的DateTime對象,並且只有一個開口(
,這沒有任何意義!
我認為當您使用右括號時,您會遇到上述錯誤
IEnumerable<DateTime> res = from x in appointments
select new DateTime { (x.Start)};
在這里,您的代碼正在嘗試(假設它是有效的)使用一些無效的語法將項目從appointments
集合投影到DateTime
另一個集合! 由於您不需要創建視圖模型類/匿名對象的對象,因此無需在此處使用new
關鍵字,因為您所需的只是Start屬性值。
解
由於Start
是DateTime
類型的屬性,因此您只需要選擇它。
List<DateTime> avaliableBookingDays = (from x in appointments
select x.Start).ToList();
要么
List<DateTime> avaliableBookingDays = appointments.Select(a=>a.Start).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.