Introduction
Return the List of strings from a List where String start with specified characters.
Background
I got a requirement in project like I have list of strings in that I have to returns the list where a string starts with specified characters. Then I wrote one small utility. This utility i am sharing now.
Using the code
Here is the small utility to filter the list where string start with specified string.
public static List<string> StartsWithStringContains(List<string> targerList, string filterStr)
{
var resultList = from resultValues in targerList
where
(resultValues.StartsWith(filterStr))
select
resultValues;
return resultList.ToList();
}
Inputs “ targerList”
- List of strings where you want search, filterStr– Filter you
are expecting start with string.
For
Example,
List<string> targerList = new List<string> { "test", "test1", "test3", "fff" };
List<string> resultList = StartsWithStringContains(targerList, "ff");
Similar implementation to search for end's with string
public static List<string> EndsWithStringContains(List<string> targerList, string filterStr)
{
var resultList = from resultValues in targerList
where (resultValues.EndsWith(filterStr))
select resultValues;
return resultList.ToList();
}
Invoke it like bellow
List<string> targerList = new List<string> { "test", "test1", "test3", "fff" };
List<string> resultList = EndsWithStringContains(targerList, "ff");
Finally String matches in any position,
public static List<string> StringContains(List<string> targerList, string filterStr)
{
var resultList = from resultValues in targerList
where
(resultValues.Contains(filterStr))
select
resultValues;
return resultList.ToList();
}
Complete
Example:
namespace StringLib
{
class Program
{
static void Main(string[] args)
{
List<string> strList = new List<string> { "test", "test1", "test3", "fff" };
strList = StartsWithStringContains(strList, "te");
foreach (string s in strList)
{
Console.WriteLine(s);
}
Console.Read();
}
public static List<string> StartsWithStringContains(List<string> targerList, string filterStr)
{
var resultList = from resultValues in targerList
where
(resultValues.StartsWith(filterStr))
select
resultValues;
return resultList.ToList();
}
public static List<string> EndsWithStringContains(List<string> targerList, string filterStr)
{
var resultList = from resultValues in targerList
where (resultValues.EndsWith(filterStr))
select resultValues;
return resultList.ToList();
}
public static List<string> StringContains(List<string> targerList, string filterStr)
{
var resultList = from resultValues in targerList
where
(resultValues.Contains(filterStr))
select
resultValues;
return resultList.ToList();
}
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.