[英]FindAll in a c# List, but varying search terms
List<DTOeduevent> newList = new List<DTOeduevent>();
foreach (DTOeduevent e in eduList.FindAll(s =>
s.EventClassID.Equals(cla)
&& s.LocationID.Equals(loc)
&& s.EducatorID.Equals(edu)))
newList.Add(e);
cla,loc,edu可以為(null或為空)或提供值-
基本上,如果cla,loc,edu全部為null,我如何簡單地返回原始列表(eduList)
或按位置搜索,按位置搜索,edu,按edu搜索,cla等--........
我的示例代碼僅在所有3個變量都具有值的情況下才創建新列表-
有沒有一種優雅的方式來做到這一點,而無需強行使用if語句?
List<DTOeduevent> newList = eduList.FindAll(s =>
(cla == null || s.EventClassID.Equals(cla))
&& (loc == null || s.LocationID.Equals(loc))
&& (edu == null || s.EducatorID.Equals(edu)));
假設值是可為空的值類型或類。 如果它們是字符串,則可以用String.IsNullOrEmpty(cla)
代替cla == null
。
IEnumerable<DTOeduevent> newList = eduList;
if (cla != null)
{
newList = newList.Where(s => s.EventClassID == cla);
}
if (loc != null)
{
newList = newList.Where(s => s.LocationID == loc);
}
if (edu != null)
{
newList = newList.Where(s => s.EducatorID == edu);
}
newList = newList.ToList();
由於延遲執行,因此Where
調用ToList
時, Where
語句應全部立即執行。 它只會在原始列表中進行一個循環。
我個人傾向於采用某種封裝您似乎在這里做的邏輯的東西:檢查找到的ID是否等於某些搜索ID。 唯一的麻煩是如何首先獲取在那里是否為空或空的檢查。
一種方法是使用靜態擴展方法:
public static class DtoFilterExtensions
{
public static bool IsIdEqual(this string searchId, string foundId) {
Debug.Assert(!string.IsNullOrEmpty(foundId));
return !string.IsNullOrEmpty(searchId) && foundId.Equals(searchId);
}
}
我也傾向於像Domenic一樣使用LINQ和IEnumerable <>,即使您可以輕松地將它與List.FindAll一起使用也是如此。 這將是一個示例用法:
public void Filter(string cla, string loc, string edu) {
var startList = new List<DTOeduevent>();
var filteredList = startList
.Where(x => x.classId.IsIdEqual(cla) && x.locationId.IsIdEqual(loc) && x.educatorId.IsIdEqual(edu));
Show(filteredList.ToList());
}
當然,在您自己的代碼中,您可以在成員變量或參數中獲得該開始列表,並且假定您有某種類似於Show()的方法要對過濾后的結果進行處理。 然后,您觸發延遲執行,如Domenic在ToList調用中所述(當然,這是LINQ的一部分提供的另一種擴展方法)。
HTH,
Berryl
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.