Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How To Get Last Index Of An Item In A C# List
WhatsApp
Mahesh Chand
6y
165.2k
0
5
100
Article
C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.
List is a generic class. You must import the following namespace before using the List<T> class.
using
System.Collections.Generic;
The LastIndexOf method returns the last index of an item if found in the List.
The following code snippet shows how to use the Contains, the IndexOf and the LastIndexOf methods.
using
System;
using
System.Collections.Generic;
namespace
ConsoleApp1
{
class
Program
{
static
void
Main(
string
[] args)
{
List<
string
> AuthorList =
new
List<
string
>();
AuthorList.Add(
"Mahesh Chand"
);
AuthorList.Add(
"Praveen Kumar"
);
AuthorList.Add(
"Raj Kumar"
);
AuthorList.Add(
"Nipun Tomar"
);
AuthorList.Add(
"Mahesh Chand"
);
AuthorList.Add(
"Dinesh Beniwal"
);
// Contains - Check if an item is in the list
if
(AuthorList.Contains(
"Mahesh Chand"
))
{
Console.WriteLine(
"Author found!"
);
}
// Find an item and replace it with new item
int
idx = AuthorList.IndexOf(
"Nipun Tomar"
);
if
(idx >= 0)
{
AuthorList[idx] =
"New Author"
;
}
Console.WriteLine(
"\nIndexOf "
);
foreach
(var author
in
AuthorList)
{
Console.WriteLine(author);
}
// Find Last index of
idx = AuthorList.LastIndexOf(
"Mahesh Chand"
);
if
(idx >= 0)
{
AuthorList[idx] =
"New Mahesh"
;
}
Console.WriteLine(
"\nLastIndexOf "
);
foreach
(var author
in
AuthorList)
{
Console.WriteLine(author);
}
}
}
}
The output from above listing is shown in below figure.
Next >>
C# List Tutorial
C# List
find item from backward in C# List
get last index
List.LastIndexOf
Up Next
Ebook Download
View all
Printing in C# Made Easy
Read by 22.4k people
Download Now!
Learn
View all
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.
Membership not found