Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How about obtaining a <strong>reference</strong> to the <strong>last item</strong> first and then use it for comparison inside the foreach loop? <strong>I am not say that you should do this as I myself would use the index based loop as mentioned by KlauseMeier</strong>. And sorry I don't know Ruby so the following sample is in C#! Hope u dont mind :-)</p> <pre><code>string lastItem = list[list.Count - 1]; foreach (string item in list) { if (item != lastItem) Console.WriteLine("Looping: " + item); else Console.Writeline("Lastone: " + item); } </code></pre> <p>I revised the following code to compare by reference not value (can only use reference types not value types). the following code should support multiple objects containing same string (but not same string object) since MattChurcy's example did not specify that the strings must be distinct and I used LINQ Last method instead of calculating the index.</p> <pre><code>string lastItem = list.Last(); foreach (string item in list) { if (!object.ReferenceEquals(item, lastItem)) Console.WriteLine("Looping: " + item); else Console.WriteLine("Lastone: " + item); } </code></pre> <p>Limitations of the above code. (1) It can only work for strings or reference types not value types. (2) Same object can only appear once in the list. You can have different objects containing the same content. Literal strings cannot be used repeatedly since C# does not create a unique object for strings that have the same content.</p> <p>And i no stupid. I know an index based loop is the one to use. I already said so when i first posted the initial answer. I provided the best answer I can in the <strong>context</strong> of the question. I am too tired to keep explaining this so can you all just vote to delete my answer. I'll be so happy if this one goes away. thanks </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload