wingskush
wingskush

Reputation: 554

Split elements of a list and retrieve only the first part from the split

I have a list say

List<string> someList = new List{"1-30","20-10","21-23","34-80"};

I need to split the list so I have with following values

 {"1","20","21","34"};

I tried

 someList
   .SelectMany(n => n.Split('-')[0])
   .ToList();

But it is not giving me the desired result.

UPDATE: Sorry everyone, Using Select solved my issue. One of those days, when you make silly mistakes

Upvotes: 1

Views: 2579

Answers (3)

Riv
Riv

Reputation: 1859

You don't need to use selectMany since you don't need to flatten your list. Using Select will return each string in the list

{"1-30", "20-100"...etc}

. Using SelectMany will actually flatten the strings into a sequence of chars resulting in

{"1", "-", "3", "0" ...etc}

So your split will result in the wrong result.

.

You just select each item in your list, split the item on the '-' char and select the first result from the split. This should give you the correct result.

List<string> someList = new List<string> { "1-30", "20-100", "21-23", "34-80" };
var splitString = someList.Select(x => x.Split('-').First()).ToList();

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You have to take the 1st part of each item and you can do with a help of Substring (i.e. take item's value up to -):

 List<string> someList = new List{
   "1-30", "20-100", "21-23", "34-80"};

 var result = someList
   .Select(item => item.Substring(0, item.IndexOf('-')))
   .ToList(); // if you want a new list

In case you want to change the existing list, just implement a loop:

 for (int i = 0; i < someList.Count; ++i)
   someList[i] = someList[i].Substring(0, someList[i].IndexOf('-'));

Edit: what's going on when you put SelectMany instead of Select.

SelectMany wants IEnumerable<T> as an outcome and since String is IEnumerable<char> you have a flatten List<char>s:

   ['1', '2', '0', '2', '1', '3', '4']

Please, notice that each string ("1", "20", "21", "34") is treated as being a collection of chars (['1']; ['2', '0']; ['2', '1']; ['3', '4'])

Upvotes: 4

Jan Martin
Jan Martin

Reputation: 51

Not as pretty as you probably want, but it does the work.

List<string> someList = new List<string>{"1-30","20-100","21-23","34-80"};
List<string> newList = new List<string>();
foreach (var v in someList)
     {
        string[] s = v.Split('-');
        newList.Add(s[0]);
     }

Upvotes: -1

Related Questions