-3

which one is the best way of doing the following and why?

string[] doubleArray = Regex
  .Split(strValue, @"[^0-9\.]+")
  .Where(c => c != "." && c.Trim() != "")
  .ToArray();  // here i have used toarray 

var doubleArray = Regex
  .Split(strValue, @"[^0-9\.]+")
  .Where(c => c != "." && c.Trim() != ""); // and here i have used var

.

Filburt
  • 17,626
  • 12
  • 64
  • 115
user3129097
  • 181
  • 9
  • 3
    The keyword `var` is only syntactic sugar, compiler uses the data type (in your example `string[]`), personally I do only use it only when VeryLongClassNamesAreUsed to make it more readable. – Cleptus Jul 17 '19 at 12:14
  • 1
    Very related, probably duplicated of https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp – Cleptus Jul 17 '19 at 12:35

1 Answers1

1

There is no implicit conversion between string[] and IEnumerable<string>.

If you want a string array you should either.

var doubleArray = Regex.Split(strValue, @"[^0-9\.]+").Where(c => c != "." && c.Trim() != "").ToArray();

or

string[] doubleArray = Regex.Split(strValue, @"[^0-9\.]+").Where(c => c != "." && c.Trim() != "").ToArray();

Do note in both cases the .ToArray() is used to enumerate the IEnumerable and get an array out of it.

In both cases the underlying type is string[] because the var keyword is only syntactic sugar.

Cleptus
  • 3,446
  • 4
  • 28
  • 34
  • @user3129097 Check my latest edit, where I add link to `var` keyword documentation, it does fully explain you your question. If you think my answer is helpful, [accept it as useful](https://stackoverflow.com/help/someone-answers). – Cleptus Jul 17 '19 at 12:31
  • "personally I do only use it only when VeryLongClassNamesAreUsed to make it more readable" could u please give me one example – user3129097 Jul 18 '19 at 06:18
  • and i noticed one more thing the second one when iterates it goes back to the .where() "Regex.Split(strValue, @"[^0-9\.]+").Where(c => c != "." && c.Trim() != "");" foreach (var item in doubleArray.AsQueryable()) { Console.WriteLine(doubleArray[i]); } i think it needs  tolist(), please suggest what should be used? – user3129097 Jul 18 '19 at 07:41