I've a collection list.
List<string> mycollections = new List<string>(new string[]
{
"MyImages/Temp/bus.jpg",
"MyImages/Temp/car.jpg",
"MyImages/Temp/truck.jpg",
"MyImages/Temp/plane.jpg",
"MyImages/Temp/ship.jpg",
});
I required only files in a List such asbus.jpg, car.jpg...... Here i do not need "MyImages/Temp/" portion of the string in the same list.
I tried with Substring and Split with Linq queries but couldn't get the expected result.
Use Path.GetFileName instead of substring like:
var fileNames = mycollections.Select(r => Path.GetFileName(r)).ToList();
For output:
var fileNames = mycollections.Select(r => Path.GetFileName(r));
foreach (var item in fileNames)
{
Console.WriteLine(item);
}
Output:
bus.jpg
car.jpg
truck.jpg
plane.jpg
ship.jpg
How about this:
mycollections.Select(s => s.Split('/').Last());
That will split each string by slashes and return the last item.
Related
Input string: "Hello_World_{0}"
I need to create a string list which is like Hello_World_1,Hello_World_2,Hello_World_3,etc... to the given input range.
I have tried below approach, it's working fine.
string input = "Hello_World_{0}";
List<string> lst = new List<string>();
foreach (int value in Enumerable.Range(1, 10))
{
lst.Add(string.Format(input,value));
}
Can I achieve the same in one liner using linq?
Select -> Fetches each item from the range of 1 -10.
Input string is replaced with each item and creates a list of strings.
ToList -> converts this into list.
string input = "Hello_World_{0}";
List<string> lst = Enumerable.Range(1, 10).Select(item => string.Format(input ,item)).ToList();
I have a list of string and an array of pattern
List<string> filePaths = Directory.GetFiles(dir, filter).ToList();
string[] prefixes = { "0.", "1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9." };
I want to replace value in filePaths for example like this:
"1. fileA" becomes "01. fileA"
"2. fileB" becomes "02. fileB"
"10. fileC" becomes "10. fileC" (since "10." is not in prefixes list)
Is there a way to do this without looping?
You can do the following, using Select:
class Program
{
static void Main(string[] args)
{
string[] prefixes = { "0.", "1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9." };
var result = Directory.GetFiles(dir, filter).Select(s => prefixes.Contains(s.Substring(0, 2)) ? "0" + s : s).ToList();
}
}
You enumerate the enumerable to check for the condition whether padding is needed, if so you pad, otherwise just return the original value.
No need for a prefixes list, you can just pad left with 0's using regex:
string input = "1. fileA";
string result = Regex.Replace(input, #"^\d+", m => m.Value.PadLeft(2, '0'));
To use on the whole list:
var filePaths = Directory.GetFiles(dir, filter).Select(s => Regex.Replace(s, #"^\d+", m => m.Value.PadLeft(2, '0'))).ToList();
I've a notepad file that has the following format:
at-2017#yahoo.com
at-2017#yahoo.com
at-2018#yahoo.com
at-2018#yahoo.com
I require the following distinct output:
at-2017#yahoo.com
at-2018#yahoo.com
Tried the following code but it doesn't get distinct values:
List<string> lst = new List<string>();
foreach (string line in File.ReadLines(values))
{
line.Distinct().ToString();
lst.Add(line);
}
I know, this may seem stupid and guessing, missed something here.
First you should read all the lines and then get the distinct lines:
var allLines = File.ReadLines(values);
var distinctLines = allLines.Distinct();
foreach(var distinctLine in distinctLines)
{
Console.WriteLine(distinctLine);
}
Distinct() operates on a collection of elements, so you don't need to use it inside the loop.
Try following:
var lst = File.ReadLines(values).Distinct();
foreach (string line in lst)
{
Console.WriteLine(line) ;
}
My code is as follows:
public List<string> connect(String query_physician, String query_institution)
{
Regex pattern = new Regex(#"(?<=""link""\:\s"")[^""]*(?="")");
MatchCollection linkMatches = pattern.Matches(customSearchResult);
var list = new List<string>();
list = linkMatches.Cast<Match>().Select(match => match.Value).ToList(); //put the links into a list?!
foreach (var item in list) //take each item (link) out of the list...
{
return item; // ...and return it?! //Error, because item is a string
}
return null;
}
Like you see, I want to return each link (as a readable list of my json result and display it in my RichTextBox, but I know, var item is a string. Otherwise it doesn´t work. Either I become an unreadable list, or a string (with string.Join(.....Cast<>()).
Do I have this right, string.Join(.....Cast<>()) adds the single strings together? Still, I don't want them together. Anyway, do you know a way to solve this problem?
By the way, return null is only a wildcard.
As I understand it is continuation of your previous question. Assuming you have this function (I simplified it a bit):
public List<string> connect(String query_physician, String query_institution)
{
...
return Regex.Matches(customSearchResult, #"(?<=""link""\:\s"")[^""]*(?="")")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
}
You can do the following:
List<string> list = connect("", "");
string linksFormatted = string.Join(",", list);
To show the content in RichTextBox:
richTextBox1.AppendText(string.Join(Environment.NewLine, list));
Look at your method signature return type is List of string no string,
so much simplest approach:
public List<string> connect(String query_physician, String query_institution)
{ ...
//restults container
List<string> resultContainer = new List<String>();
Regex pattern = new Regex(#"(?<=""link""\:\s"")[^""]*(?="")");
MatchCollection linkMatches = pattern.Matches(customSearchResult);
var list = new List<string>();
list = linkMatches.Cast<Match>().Select(match => match.Value).ToList(); //put the links into a list?!
foreach (var item in list) //take each item (link) out of the list...
{
//add item to list
resultContainer.Add(item);
}
return resultContainer;
}
I have a big list of filenames, some of which contain whitespace, for example
"\project summary version 2.xls"
or
"\production q3.pdf"
These file names are stored in object on string format.
Q: I would like to be able to query the object with maybe linq and collect all these illegal filenames together?
You can do something like this:
List<string> filenames = ...
List<string> filenamesWithSpaces = filenames.Where(f => f.Contains(" ")).ToList();
You have many options.
One way I'd do this would be to use string.Split and check it's result:
List<string> filenames = new List<string>(); // fill this list in some way.
var filesResult = filenames.Select(f => new { Filename = f, HasSpaces = f.Split(' ').Count() > 1 });
var filesWithSpaces = filesResult.Where(f => f.HasSpaces);