Pergunta

I am using DevExpress XAF. I have a list view. In the list view the user can select multiple rows. I need to make sure that all the cells of a particular column/property hold the same value. Otherwise I need to throw an exception.

So for example, if a user selects 3 rows, I need to make sure the 3 values in the Trucker column are the same. Here is my code so far:

 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.");                       
    }


  }
Foi útil?

Solução

Try something like this, using LINQ (assuming lr is your 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.");

I haven't used the DevExpress controls. It looks like you might have to adjust the above using:

... = lr.SelectedObjects.Cast<PurchaseLoad.Trucker>()...

In your original code, your syntax is off. You compare two values using:

if (value1 == value2)

if (value1 != value2)

Not:

if (value1 == value2 == true)

if (value1 == value2 == false)

Final working solution (from EB's comment):

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.");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top