-3

I have a List of strings with the items such-

Titanic, Leonardo Decaprio  
Mission Impossible, Tom Cruise  

Is there any way such that I can get only the first substring before the comma? In above case the expected output for List<string> should be -

Titanic
Mission Impossible
Arpit Gupta
  • 1,209
  • 1
  • 22
  • 39
  • 4
    Possible duplicate of [How can I split a string with a string delimiter?](http://stackoverflow.com/questions/8928601/how-can-i-split-a-string-with-a-string-delimiter) – MicroVirus Jun 18 '16 at 09:22
  • @MicroVirus Not a duplicate of it. The answer I got below was the one I was looking for. – Arpit Gupta Jun 21 '16 at 12:31
  • It a duplicate. The only difference is that you want to do this for every element of the list. If you can't apply the answer in that duplicate (using `Split`) with how to do that for each element of the list, then you need to really get back to the basics of learning C#. – MicroVirus Jun 21 '16 at 12:36
  • Okay, Thank you..!! – Arpit Gupta Jun 22 '16 at 03:55

2 Answers2

5

You can use Split method and then using Select method get only the first part.

list.Select(x=> x.Split(',')[0]);

You can use Substring and IndexOf instead of Split

list.Select(x => x.Substring(0, x.IndexOf(',')));

If you are not sure that every string contains comma you can check it, for example this way

list.Select(x => x.Substring(0, x.IndexOf(',') > 0 ? x.IndexOf(',') : x.Length))
Valentin
  • 5,380
  • 2
  • 24
  • 38
1

You will also need to call .ToList() method otherwise it will not cast the resulting list into List<string> and throw exception because resulting list would of type System.Collections.Generic.IEnumerable<string> and your's is of List<string

List<string> list = new List<string>() { "Titanic, Leonardo Decaprio", " Mission Impossible, Tom Cruise" };
list = list.Select(x => x.Split(',')[0]).ToList();
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40