我有3个变量:
我想做的事情:如果可以在别名列表中找到AssociateInfo的属性Alias,我想在已定义的Alias前面放一个星号*。
我上次中断的地方是未注释的别名,并且可以想象,它抛出了错误。我有点期望,但是一口气就无法完成所需的工作。这有可能吗?
请在下面查看我的代码,感谢您的帮助!
List<int> wqReqIds = requests.Select(x => x.WorkQueueRequestId).ToList();
var aliases = db.WorkQueueRequestDetails.Where(w => wqReqIds.Contains(w.WorkQueueRequestId))
.GroupBy(x => x.AssociatesHistory.Alias)
.Where(g => g.Count() > 1).ToList();
var allWqAssociates = db.WorkQueueRequestDetails.Where(w => wqReqIds.Contains(w.WorkQueueRequestId))
.Select(x => new AssociateInfo
{
WorkQueueRequestId = x.WorkQueueRequestId,
//Alias = x.AssociatesHistory.Alias,
Alias = aliases.Where(y => y.Key == x.AssociatesHistory.Alias).Any()
? "***" + x.AssociatesHistory.Alias
: x.AssociatesHistory.Alias,
//Alias = aliases.Contains(x.AssociatesHistory.Alias)
// ? "***" + x.AssociatesHistory.Alias
// : x.AssociatesHistory.Alias,
Name = x.AssociatesHistory.FirstName + (x.AssociatesHistory.MiddleInitial == null ? " " : " " + x.AssociatesHistory.MiddleInitial + " ") + x.AssociatesHistory.LastName
})
.ToList();
答案 0 :(得分:1)
下面的LINQ已经过测试,应该可以工作。注意最后一个变量,我们在选择之前调用ToList。这样我们就可以使用其他函数,例如ToString()和三元运算符,而无需EF尝试对其进行转换。由于您没有提供,因此数据模型可能会有一些变化。我还在全名上实现了ToString覆盖,您可以在此答案的底部看到。
var wqReqIds = requests.Select(x => x.WorkQueueRequestId).ToList();
var aliases = db.WorkQueueRequestDetails.Where(x => wqReqIds.Contains(x.WorkQueueRequestId))
.GroupBy(x => x.AssociatesHistory.Alias)
.Where(x => x.Count() > 1)
.Select(x => x.Key)
.ToList();
var allWqAssociates = db.WorkQueueRequestDetails.Where(w => wqReqIds.Contains(w.WorkQueueRequestId))
.ToList()
.Select(x => new AssociateInfo
{
WorkQueueRequestId = x.WorkQueueRequestId,
Alias = aliases.Any(y => y == x.AssociatesHistory.Alias)
? "***" + x.AssociatesHistory.Alias
: x.AssociatesHistory.Alias,
Name = x.AssociatesHistory.ToString()
});
具有ToString实现的模型
public class AssociatesHistory
{
public string Alias { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return $"{FirstName} {MiddleInitial} {LastName}";
}
}