Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first occurence of element in List C# with LINQ?

Tags:

c#

list

linq

I have the following list

List<string> listString = new List<string>() { "UserId", "VesselId", "AccountId", "VesselId" };

I would like to use a Linq operator which removes only the first occurrence of VesselId.

like image 993
DenisSuarez Avatar asked Jun 10 '16 12:06

DenisSuarez


3 Answers

you can not change the original collection with LINQ, so the closest thing would be:

var index = listString.IndexOf("VesselId");
if(index>-1)
   listString.RemoveAt(index);

EDIT 1:

According to research done by Igor Mesaros, I ended up implementing the logic which resides in the List.Remove method, so an even simpler solution would be:

listString.Remove("VesselId");
like image 76
Eyal Perry Avatar answered Nov 14 '22 22:11

Eyal Perry


If you have a simple list of strings or some other primitive type, then you can just call:

listString.Remove("VesselId");

as mentioned by @Eyal Perry

If you have a huge none primitive list, this is the most efficient

class MyClass
{
   string Name {get; set;}
}

var listString = new List<MyClass>() {/* Fill in with Data */};
var match = listString.FirstOrDefault(x => x.Name == "VesselId");

if(match != null)
     listString.Remove(match);
like image 24
Igor Meszaros Avatar answered Nov 14 '22 22:11

Igor Meszaros


If what you are looking to do is get a distinct list then you have an extension method for that listString.Distinct()

like image 38
Gilad Green Avatar answered Nov 15 '22 00:11

Gilad Green