简体   繁体   English

如何检查LINQ中的数组是否不是null?

[英]How to check if array is not null in LINQ?

I Have this where statement in LINQ:我在 LINQ 中有这个 where 语句:

(users != null && users.Contains(x.Appointment.UserId))

users is an int[] . users 是一个int[] When i run this code i have an exception:当我运行此代码时出现异常:

Unable to create a null constant value of type 'System.Int32[]'.无法创建“System.Int32[]”类型的 null 常量值。 Only entity types, enumeration types or primitive types are supported in this context.在此上下文中仅支持实体类型、枚举类型或原始类型。

What should i do?我应该怎么办?

I had a similar problem.我有一个类似的问题。 Assuming you are starting with something like this:假设您从这样的事情开始:

var filtered = appointments
    .Where(x => users != null && users.Contains(x.Appointment.UserId));

As @CarstenKönig suggests, try moving the null check outside of the Where clause:正如@CarstenKönig 建议的那样,尝试将 null 检查移到 Where 子句之外:

var filtered = users != null ? 
    appointments.Where(x => users.Contains(x.Appointment.UserId)) :
    appointments;

That means the null check is handled by C#, and LINQ to Entities doesn't attempt to convert it to SQL.这意味着 null 检查由 C# 处理,而实体的 LINQ 不会尝试将其转换为 SQL。

As others suggested you could move bool check outside the closure and use resulting bool in your Where statement:正如其他人所建议的那样,您可以将 bool check 移到闭包之外,并在Where语句中使用结果 bool :

var usersNotNull = users != null;
var users = users == null ? new string[0] : users;
query.Where(x => usersNotNull && users.Contains(x.Appointment.UserId));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM