xsharp.eu • X# Example Project for various DotNet functionality - Page 4
Page 4 of 4

X# Example Project for various DotNet functionality

Posted: Fri Aug 27, 2021 7:23 am
by wriedmann
Hi Robert,
I use foreach whenever it is possible, but many times unfortunately it is not because I need the current index.
And with foreach I have no chance to detect if I'm at the first or at the last element (specially for the last element very often I need special rules).
Wolfgang

X# Example Project for various DotNet functionality

Posted: Fri Aug 27, 2021 7:29 am
by Chris
Hi Wolfgang,
wriedmann wrote:,
as I wrote before: IMHO starting an index with 0 is illogic, but since we have no influence on this we have to accept that.
What makes it even more confusing in X# is the difference between arrays (for compatibility to VO/Clipper/VFP the first array index is 1) and collections (where the first array index is 0). But again: it is so, we cannot change it, so we have to accept it.
I understand what you're saying, it's that it's my nature to not accept "we have to accept it even though it doesn't make sense" for an answer :)

X# Example Project for various DotNet functionality

Posted: Fri Aug 27, 2021 10:01 am
by VR
Hello Wolfgang,

there is an overload of Select, that could help you get the index

Code: Select all

var items = new List<string> { "a", "b", "c"};
foreach(var item in items.Select((v, i) => new { value = v, index = i }))
   Console.WriteLine($"{item.index} -> {item.value}");
Of course, this adds a little bit of overhead. An other alternative for when you just need the first or last element is

Code: Select all

var items = new List<string> { "a", "b", "c"};
var first = items.FirstOrDefault();
var last = items.LastOrDefault();
foreach(var item in items)
   if (item == first)
      // ...
Volkmar

X# Example Project for various DotNet functionality

Posted: Sun Aug 29, 2021 7:11 am
by wriedmann
Hi Volkmar,
thank you very much!
I try to use LinQ only when it simplifies my code very much - otherwise I try to write my code in the simpliest possible mode because it helps me to keep my code maintainable for many years.
Wolfgang