Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
actually i had to use foreach loop for accessing each item from collection but i want

to access the any one of item from collection i.e access only one item from

collection.don't want to access the remaining items.

foreach loop like as

C#
foreach(string item in collection)
{


}


i want to access the any one of item from collection i.e access only one item from

collection.don't want to access the remaining items.


please help me.

thank u.
Posted
Comments
[no name] 29-Jun-15 7:42am    
collection[index]
ZurdoDev 29-Jun-15 7:42am    
collection[8], like this?

If your collection implements an indexer, you can directly access an item.
Using Indexers (C# Programming Guide)[^] provides some details about this.

Here is a video that shows indexer examples - Part 64 - C# Tutorial - How and where are indexers used in .net [^].
 
Share this answer
 
v2
C#
// get the first item if there is one
string x = collection.FirstOrDefault();

// or get the first one that confirms to a condition, such as it
// starts with "A"
string y = collection.FirstOrDefault(s => s.StartsWith("A"));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900