gpt4 book ai didi

LINQ - if 条件

转载 作者:行者123 更新时间:2023-12-02 23:59:25 28 4
gpt4 key购买 nike

在代码中,注释部分是我需要解决的问题...有没有办法在 LINQ 中编写这样的查询?我需要这个,因为我需要根据状态进行排序。

var result = (
from contact in db.Contacts
join user in db.Users on contact.CreatedByUserID equals user.UserID
join deal in db.Deals on contact.ContactID equals deal.ContactID into deals
orderby contact.ContactID descending
select new ContactListView
{
ContactID = contact.ContactID,
FirstName = contact.FirstName,
LastName = contact.LastName,
Email = contact.Email,
Deals = deals.Count(),
EstValue = deals.Sum(e => e.EstValue),
SalesAgent = user.FirstName + " " + user.LastName,
Tasks = 7,
// This is critical part
if(Deals == 0) Status = "Prospect";
else
Status = "Client";
// End of critical part...
})
.OrderBy(filterQuery.OrderBy + " " + filterQuery.OrderType)
.Where(filterQuery.Status);

最佳答案

Status = (deals.Count() == 0 ? "Prospect" : "Client")

这使用 "Conditional operator"

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

编辑:您可以进行如下组合:

Status = (deals.Count() == 0 ? "Prospect" : (deals.Count() == 1 ? "Client" : "Other"))

在本例中,您经常使用 deals.Count(),因此您可以使用 LINQ let 语法将结果存储在临时变量中:

var result = (
from contact in db.Contacts
join user in db.Users on contact.CreatedByUserID equals user.UserID
join deal in db.Deals on contact.ContactID equals deal.ContactID into deals
let dealCount = deals.Count()
... // Continue here
Status = (dealCount == 0 ? "Prospect" : (dealCount == 1 ? "Client" : "Other"))

关于LINQ - if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3051786/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com