Home > Software engineering >  Getting a list of strings with only the first and last character from another list LINQ
Getting a list of strings with only the first and last character from another list LINQ

Time:11-25

From a given list of strings I need to use LINQ to generate a new sequence of strings, where each string consists of the first and last characters of the corresponding string in the original list.

Example:

stringList: new[] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" },
expected: new[] { "ee", "fg", "jw" });
list2 = stringList.Select(e => {e = ""   e[0]   e[e.Length - 1]; return e; }).ToList();

This is what I've tried, it works, but I need to use LINQ to solve the problem and I'm not sure how to adapt my solution.

CodePudding user response:

As mentioned in the comment that Select is already part of LINQ, you can use this code.var output = arr.Select(x => new string(new char[] { x.First(), x.Last() })).ToList();

CodePudding user response:

Here you go:

var newList = stringList.Select(e => $"{e[0]}{e[e.Length - 1]}").ToList();

CodePudding user response:

appraoch with Linq and String.Remove()

string[] input = new[] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" };
string[] result = input.Select(x => x.Remove(1, x.Length - 2)).ToArray();
  • Related