0

I use form collection to retrieve values from dynamically cloned form elements/values in controller

string[] vi = collection["VoteInfoCatId"].Split(char.Parse(","));

vi can have values of 1,2 or 3 I want to create a condition where I could check to make sure on all occasions vi should always have these 3 different values without any duplicates I was doing it like

Where vi[0]!=vi[1] && vi[0]!=vi[2]  && vi[1]!=vi[2] 

Is there a better way to do this?

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Diin
  • 565
  • 11
  • 41

1 Answers1

1

It depends how you're handling your "has duplicated values" case, in either case, LINQ is your friend.

If you want to detect duplicates and take action on them, you can group by the string's unique values and see if there are any with a count of more than 1. For example:

if (vi.GroupBy(m => m).Any(m => m.Count() != 1)) {
    // Has duplicates
}

If you're wanting to simply remove the duplicates you can do:

var distinctVi = vi.Distinct();

As a side note, your call to char.Parse(string) is redundant, you should simply use the char directly. Note that " (double quotes) is a string, whilst ' (single quote) is a char, so the following would work:

var vi = collection["VoteInfoCatId"].Split(',');
Rudi Visser
  • 21,350
  • 5
  • 71
  • 97