Linq用另一个值替换空/空值 [英] Linq replace null/empty value with another value
问题描述
在sql server中,我创建了一些视图,可以在其中检查空值,如果需要,可以将其替换为默认值(即ISNULL(PrimaryPhone,'No Primary#')AS PrimaryPhone.我在asp中使用了很多视图.网络表单应用程序,但是我现在正在学习MVC 4,并希望从头开始.
In sql server I create views where I can check for null values and replace them with a default if I want (i.e. ISNULL(PrimaryPhone, 'No Primary #') AS PrimaryPhone. I used a lot of views in my asp.net web forms application, but I am now learning MVC 4 and want to start out right.
我为我的客户表设置了模型,控制器和视图.我希望能够将null/empty值替换为("Not Entered")或类似的值. 我相信这需要在控制器中进行,如果我错了,请纠正我.
I have a model, controller and view set up for my client table. I would like to be able to replace null/empty values with ("Not Entered") or something like that. I believe this needs to go in the controller, please correct me if I'm wrong.
我看到了一个使用hasvalue的示例,但无法通过智能感知使用.
I saw an example that uses hasvalue, but it is not available through intellisense.
如何在模型中不使用DefaultValue的情况下替换空/空值?
How would I replace empty/null values without using DefaultValue in my model?
谢谢
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = x.emailadd.DefaultIfEmpty("No Email"),....
推荐答案
You can use the ?? operator to set a default value when something is null:
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = x.emailadd ?? "No Email", ...
如果您需要更多控制,例如检查null和empty,还可以使用
If you need more control, for example checking for both null and empty, you can also use the ?: operator (also known as the "conditional operator" or "ternary operator"):
var result = db.Clients.Select(x => new
{
CustomerID = x.CustomerID,
UserID = x.UserID,
FullName = x.FullName,
EmailAdd = string.IsNullOrEmpty(x.emailadd) ? "No Email" : x.emailadd, ...
这篇关于Linq用另一个值替换空/空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!