Jimbo Jones
Jimbo Jones

Reputation: 1002

Loop through a List<string> but only take a part of each string inside

I am wondering if anyone can help me, I am trying to loop through a list of strings but only take the part to the left of ":" but not including the ":" I can do this with the approach below but I am trying to implement this by using Linq instead. Any help would be greatly appreciated.

        List<string> Results = new List<string>();

        List<string> strings = new List<string>
        {
            "121:sdfdsfds",
            "122:sdfdsfds",
            "123:sdfdsfds"
        };

        for (var i = 0; i < strings.Count; i++)
        {
            string[] tokens = strings[i].Split(':');
            if (tokens.Any())
            {
                Results.Add(tokens[0]);
            }
        }

Upvotes: 2

Views: 2412

Answers (5)

IAbstract
IAbstract

Reputation: 19881

Use the Select method (System.Linq namespace)

class Program
{
    static void Main(string[] args)
    {
        List<string> strings = new List<string>
        {
            "121:sdfdsfds",
            "122:sdfdsfds",
            "123:sdfdsfds"
        };

        List<string> Results = strings
            .Select(s => s.Split(':')[0])
            .ToList();

        Results.ForEach(s => Console.WriteLine(s));

        Console.ReadKey();
    }
}

Output:

121
122
123

Upvotes: 4

Rufus L
Rufus L

Reputation: 37020

You can take each item of the string array, split it, and return index[0] all inside a select statement:

var results = strings.Select(i => i.Split(':')[0]).ToList();

If there's a chance that some items will be empty and you don't want to include them, you can use this syntax on the string.Split method:

var results = strings
    .Select(i => i.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries)
        .FirstOrDefault())
    .Where(i => i != null)
    .ToList();

Upvotes: 1

Deadzone
Deadzone

Reputation: 814

Method chain syntax:

List<string> Results = strings.Select(t => t.Split(':'))
       .Where(tokens => tokens.Any())
       .Select(tokens => tokens[0]).ToList();

Query syntax:

List<string> Results = (from t in strings
    select t.Split(':')
    into tokens
    where tokens.Any()
    select tokens[0]).ToList();

Upvotes: 3

Team Kitsune
Team Kitsune

Reputation: 101

Use forEach, strings.ForEach(x => Results.Add(x.Split(':')[0]));

Upvotes: 0

George Alexandria
George Alexandria

Reputation: 2936

List<string> Results = strings
    .Select(item => item.Split(':').FirstOrDefault())
    .Where(item => item != null).ToList();

Upvotes: 1

Related Questions