Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring with linq?

Tags:

string

c#

linq

I've got collection of words, and i wanna create collection from this collection limited to 5 chars

Input:

Car
Collection
Limited
stackoverflow

Output:

car
colle
limit
stack

word.Substring(0,5) throws exception (length)

word.Take(10) is not good idea, too...

Any good ideas ??

like image 828
user278618 Avatar asked Mar 08 '10 15:03

user278618


People also ask

How to get Substring in LINQ?

Substring(0,5)) select new { Name = AccountName }); int c = lQuery. ToList(). Count();

What is substring in C# with example?

Substring Method (int startIndex, int length) This method is used to extract a substring that begins from specified position describe by parameter startIndex and has a specified length. If startIndex is equal to the length of string and parameter length is zero, then it will return nothing substring.


2 Answers

var words = new [] { "Car", "Collection", "Limited", "stackoverflow" };
IEnumerable<string> cropped = words.Select(word => 
                                    word[0..Math.Min(5, word.Length)]);

Ranges are available in C# 8, otherwise you'll need to do:

IEnumerable<string> cropped = words.Select(word => 
                                    word.Substring(0, Math.Min(5, word.Length)));
like image 135
Paul Ruane Avatar answered Sep 17 '22 13:09

Paul Ruane


LINQ to objects for this scenario? You can do a select as in this:

from w in words
select new
{
  Word = (w.Length > 5) ? w.Substring(0, 5) : w
};

Essentially, ?: gets you around this issue.

like image 32
Brian Mains Avatar answered Sep 17 '22 13:09

Brian Mains