如果FirstOrDefault返回null,则返回列表中的第一项

我有一个产品List ,我需要从列表中获取具有我从查询字符串参数获得的特定产品Id的项目。 但是,我可能并不总是将产品Id传递给我。 如果我没有产品Id ,我需要默认使用列表中的第一个产品。

目前我有:

 @Model.Products.FirstOrDefault(x => x.Id == productId); 

这只是选择具有该特定Id的产品,如果没有,则默认为null

有没有办法实现我想要的?

这听起来像你想要的:

 var product = productId == null ? Model.Products.FirstOrDefault() : Model.Products.FirstOrDefault(x => x.Id == productId); ... @product 

或者你的意思是:

 @(Model.Products.FirstOrDefault(x => x.Id == productId) ?? Model.Products.FirstOrDefault()) 

如果你尝试这样的事情会怎么样?

 @if (productId != null) // assuming it's nullable { @Model.Products.FirstOrDefault(x => x.Id == productId) } else { @Model.Products.FirstOrDefault() } 

我知道这可能看起来有点麻烦,但它很清楚它正在做什么(想想如果其他人必须维护它)它应该工作。

但实际上我可能宁愿在ViewModel设置它,然后只访问我知道正确的值。

嘿检查这可能会对你有所帮助

MSDN链接: http : //msdn.microsoft.com/en-us/library/bb340482.aspx

 List months = new List { }; // Setting the default value to 1 after the query. int firstMonth1 = months.FirstOrDefault(); if (firstMonth1 == 0) { firstMonth1 = 1; } Console.WriteLine("The value of the firstMonth1 variable is {0}", firstMonth1); // Setting the default value to 1 by using DefaultIfEmpty() in the query. int firstMonth2 = months.DefaultIfEmpty(1).First(); Console.WriteLine("The value of the firstMonth2 variable is {0}", firstMonth2); /* This code produces the following output: The value of the firstMonth1 variable is 1 The value of the firstMonth2 variable is 1 */