我正在使用DevExpress XAF。我有一个列表视图。在列表视图中,用户可以选择多行。我需要确保特定列/属性的所有单元格保持相同的值。否则我需要抛出异常。
因此,例如,如果用户选择3行,我需要确保Trucker列中的3个值相同。到目前为止,这是我的代码:
if (lr.PurchaseLoad.Trucker != null)
{
if (lr.PurchaseLoad.Trucker.Name == lr.PurchaseLoad.Trucker.Name == true)//Is this correct?
{
// What am I comparing here?
}
else if (lr.PurchaseLoad.Trucker.Name.Equals(lr.PurchaseLoad.Trucker.Name) == false)
{
throw new UserFriendlyException("Please make sure your selected records have the same Trucker assigned.");
}
}
答案 0 :(得分:1)
使用LINQ尝试这样的事情(假设lr
是你的ListView
):
var distinctNames = lr.SelectedItems.Cast<PurchaseLoad.Trucker>()
.Where(x => x != null)
.Select(x => x.Name)
.Distinct()
.Count();
if (distinctNames == 0)
throw new UserFriendlyException("Make at least one selection.");
else if (distinctNames > 1)
throw new UserFriendlyException("Please make sure your selected records have the same Trucker assigned.");
我还没有使用DevExpress
控件。您可能需要使用以下方法调整上述内容:
... = lr.SelectedObjects.Cast<PurchaseLoad.Trucker>()...
在原始代码中,您的语法已关闭。您可以使用以下方法比较两个值:
if (value1 == value2)
if (value1 != value2)
不
if (value1 == value2 == true)
if (value1 == value2 == false)
最终工作解决方案(来自EB的评论):
foreach (LoadRelationship trucker in View.SelectedObjects)
{
var distinctNames =
View.SelectedObjects.Cast<LoadRelationship>()
.Where(x => x != null)
.Select(x => x.PurchaseLoad.Trucker.Name)
.Distinct()
.Count();
if (distinctNames > 1)
throw new UserFriendlyException(
"Please make sure your assigned Truckers are the same.");
}