[英]How do you sort a generic list in C# and allow NULL items to appear first in the list?
[英]How to check if any of the items in the generic list is null or 0
我正在使用下面的代碼行來檢查通用列表中的任何項目是否為空或 0
if (Region.Dept.College[index].Student.Any(
c => c.Age=null ||
c.Name !=null ||
c.code!=null ||
c.Fees!=null ||
c.Gender!=null ||
c.M1!=null ||
c.grade!= null ||
c.caste!= null ||
c.castespecified!= null ||
c.GradeLevel!= null ||
c.Gradelevelspecified!= null ||
c.FeePercent!= 0 ||
c.FeePercentSpecified != null ||
c.StudentRegistrationID!= null)
但是即使所有項目都是空的,它仍然會進入 if 循環,這是不正確的。 請幫我糾正這個問題。
變量是樣本
You want to check whether any student has a any null property (ie c => c.Age==null || c.Name ==null ||..
) and if so not enter the loop, so it should be:
if(!Region.Dept.College[index].Student.Any(condition))
{
//loop code here, all students valid
}
目前您正在測試相反的情況 - 您正在測試是否有任何學生有效,而不是如果所有學生都有效(這相當於沒有任何無效)。 還要檢查您的 null 檢查 - 根據您需要不同檢查的數據類型,即string.IsNullOrEmpty()
用於字符串等。
另外我假設c.Age=null
只是一個錯字,否則不會編譯。
看起來您錯誤地包括null
年齡
編輯:雖然,我可能會將驗證卸載到返回 boolean 的方法,然后只需在If
中引用該方法。 To keep it clean, make a function which takes the object as a parameter, then in that function do all this validation and return a boolean. 像AllValuesEmpty
這樣的話,你的謂詞應該只是 function 的結果。
這是更好的做法,因為稍后如果您想向 object 添加一些內容或更改驗證它是否為空的方式,您只需更改一種方法,而不必搜索冗長、復雜的If
條件。
EDIT2:還要注意 C# 區分NULL
值和任何空值。 其中NULL
表示“沒有任何可用於解決此問題的參考”,而空表示“有為此參考的空間,但沒有任何有用的存儲在那里”
也許您的屬性在 object 的構造函數中使用默認值進行了初始化。 也許他們是空的,但不是NULL
c => c.Age=null
應該
c => c.Age==null
您基本上將所有學生的 Age 分配給 null 。
You have c => c.Age=null ||...
that supposed to be c => c.Age != 0
?
要確定哪個檢查失敗,請在緊隨其后的斷點下逐一執行它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.