Suppose we have a list of strings like below:
List<string> myList = new List<string>(){"one", "two", "three", "four"};
There are some items with the length of more than 3.
By the help of Linq I want to divide them into new items in the list, so the new list will have these items:
{"one", "two", "thr", "ee", "fou", "r"};
Don't ask me why Linq. I am a Linq fan and don't like unLinq code :D
For real code basic for
would likely be better (i.e. as shown in other answer.
If you really need LINQ split string into 3-letter chunks and than merge all with SelectMany
:
var list = new[]{"", "a", "abc","dee","eff","aa","rewqs"};
var result = list
.Select(
s =>
Enumerable.Range(0, s.Length / 3 +
(s.Length == 0 || (s.Length % 3 > 0) ? 1 : 0))
.Select(i => s.Substring(
i * 3,
Math.Min(s.Length - i * 3, 3))))
.SelectMany(x=>x);
Range
creates enumerable for all segments of the string (which is either length/3 if all pieces are exactly 3 characters, or one more if last one is shorter than 3 character).
.Select(i => s.Substring...
splits string into chunks of 3 or less characters (need to carefully adjust length to avoid index out of range error)
.SelectMany
combines list of list of 3 character segments into flat list of 3 character segments.
Note: This LINQ code should be used for entertainment/learning purposes. If you must use similar LINQ solution in production code at least convert splitting of string into more readable helper function.
I'm not sure you can do that with Linq. Here is a non-linq solution:
for (int x = 0; x < myList.Count; x++)
{
if (myList[x].Length > 3)
{
var oldString = myList[x];
myList[x] = oldString.Substring(0, 3);
myList.Insert(x + 1, oldString.Substring(3));
}
}
Edit: Apparently you can do that with Linq. Well, this is a non-linq solution anyways...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With