X# Example Project for various DotNet functionality

This forum is meant for anything you would like to share with other visitors
User avatar
wriedmann
Posts: 3755
Joined: Mon Nov 02, 2015 5:07 pm
Location: Italy

X# Example Project for various DotNet functionality

Post 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
Wolfgang Riedmann
Meran, South Tyrol, Italy
wolfgang@riedmann.it
https://www.riedmann.it - https://docs.xsharp.it
User avatar
Chris
Posts: 4898
Joined: Thu Oct 08, 2015 7:48 am
Location: Greece

X# Example Project for various DotNet functionality

Post 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 :)
Chris Pyrgas

XSharp Development Team
chris(at)xsharp.eu
VR
Posts: 102
Joined: Sun Aug 23, 2020 3:07 pm
Location: Italy

X# Example Project for various DotNet functionality

Post 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
User avatar
wriedmann
Posts: 3755
Joined: Mon Nov 02, 2015 5:07 pm
Location: Italy

X# Example Project for various DotNet functionality

Post 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
Wolfgang Riedmann
Meran, South Tyrol, Italy
wolfgang@riedmann.it
https://www.riedmann.it - https://docs.xsharp.it
Post Reply