这些功能在逻辑上是否相同?

时间:2013-12-11 15:07:23

标签: c# linq

我的答案是肯定的?当时的结果将是相同的。

public bool CustomValidationDublicateName(string sysPriority)
{
    var systemPriories = (this.gridView.Items.SourceCollection as IEnumerable<SystemPriority>).Where(item => item.ID > 0).ToList();
    var selectedItem = this.gridView.SelectedItem as SystemPriority;
    foreach (SystemPriority item in systemPriories)
    {
        if (item.Title == sysPriority && item != selectedItem) 
            return false;
    }           
    return true;
}

public bool CustomValidationDublicateName2(string sysPriority)
{
    var systemPriories = (this.gridView.Items.SourceCollection as IEnumerable<SystemPriority>).Where(item => item.ID > 0).ToList();
    var selectedItem = this.gridView.SelectedItem as SystemPriority;
    return systemPriories.All(item => item.Title != sysPriority || item == selectedItem);
}


public bool CustomValidationDublicateName(string sysPriority)
{
    var systemPriories = (this.gridView.Items.SourceCollection as IEnumerable<SystemPriority>).Where(item => item.ID > 0).ToList();
    var selectedItem = this.gridView.SelectedItem as SystemPriority;
    return systemPriories.All(item => item.Title == sysPriority && item != selectedItem);
}

我的答案是肯定的?当时的结果将是相同的。

2 个答案:

答案 0 :(得分:4)

但是,您应该摆脱ToList(),并合并Where()All()过滤器:

public bool CustomValidationDublicateName2(string sysPriority)
{
    return (this.gridView.Items.SourceCollection as IEnumerable<SystemPriority>)
         .All(item => item.ID < 0 
                   || item.Title != sysPriority 
                   || item == (SystemPriority)this.gridView.SelectedItem);
}

答案 1 :(得分:3)

是的,这些功能是平等的。

查看De Morgan's Laws以了解原因!(A && B) == !A || !B。然后你会看到条件做同样的事情。

!(item.Title == sysPriority && item != selectedItem)
    ==
(item.Title != sysPriority || item == selectedItem)