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);
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'm trying to write a lambda expression to compare members of a list to a string, but I also need to catch elements in the list that might have their letter scrambled up.
Here's code I got right now
List<string> listOfWords = new List<String>() { "abc", "test", "teest", "tset"};
var word = "test";
var results = listOfWords.Where(s => s == word);
foreach (var i in results)
{
Console.Write(i);
}
So this code will find string "test" in the list and will print it out, but I also want it to catch cases like "tset". Is this possible to do easily with linq or do I have to use loops?
How about sorting the letters and seeing if the resulting sorted sequences of chars are equal?
var wordSorted = word.OrderBy(c=>c);
listOfWords.Where(w => w.OrderBy(c=>c).SequenceEqual(wordSorted));
I have a list of strings in a List container class that look like the following:
MainMenuItem|MenuItem|subItemX
..
..
..
..
MainMenuItem|MenuItem|subItem99
What I am trying to do is transform the string, using LINQ, so that the first item for each of the tokenised string is removed.
This is the code I already have:
protected static List<string> _menuItems = GetMenuItemsFromXMLFile();
_menuItems.Where(x => x.Contains(menuItemToSearch)).ToList();
First line of code is returning an entire XML file with all the menu items that exist within an application in a tokenised form;
The second line is saying 'get me all menu items that belong to menuItemToSearch'.
menuItemToSearch is contained in the delimited string that is returned. How do I remove it using linq?
EXAMPLE
Before transform: MainMenuItem|MenuItem|subItem99
After transform : MenuItem|subItem99
Hope the example illustrates my intentions
Thanks
You can take a substring from the first position of the pipe symbol '|' to remove the first item from a string, like this:
var str = "MainMenuItem|MenuItem|subItemX";
var dropFirst = str.Substring(str.IndexOf('|')+1);
Demo.
Apply this to all strings from the list in a LINQ Select to produce the desired result:
var res = _menuItems
.Where(x => x.Contains(menuItemToSearch))
.Select(str => str.Substring(str.IndexOf('|')+1))
.ToList();
Maybe sth like this can help you.
var regex = new Regex("[^\\|]+\\|(.+)");
var list = new List<string>(new string[] { "MainMenuItem|MenuItem|subItem99", "MainMenuItem|MenuItem|subItem99" });
var result = list.Where(p => regex.IsMatch(p)).Select(p => regex.Match(p).Groups[1]).ToList();
This should work correctly.
I have a List<string> with some 10 strings.
The values are as follows:
\\Server\Site\MySite\File1.xml
\\Server\Site\MySite\File2.xml
\\Server\Site\MySite\File2.xml
.......................
\\Server\Site\MySite\File10.xml
I need to extract \MySIte\File1.xml to \MySite\File10.xml and store in another list.
I tried to use Split keyword, with another list to populate the splitted string. But it doesn't seem to give the correct answer.
Below is the code:
for(int index=0;index<list.Count;list++)
{
string[] myArray=list[index].Split('\\');
for(int innerIndex=0;innerIndex<myArray.Length;innerIndex++)
{
anotherList[innerIndex]=myArray[2]+"\\"+myArray[3];
}
}
Experts please help.
You don't need to work too hard if you know the input of all the strings
str.Substring(str.IndexOf("\\MySite"))
One word: LINQ!
var results = (from x in source
let parts = x.Split('\\')
select String.Join("\\", parts.Skip(1)).ToArray();
You can use following code.
List<string> source = new List<string>();
source.Add(#"\\Server\Site\MySite\File1.xml");
source.Add(#"\\Server\Site\MySite\File2.xml");
source.Add(#"\\Server\Site\MySite\File2.xml");
source.Add(#"\\Server\Site\MySite\File10.xml");
foreach(string s in source)
{
string[] parts = s.Split(new string[]{ Path.DirectorySeparatorChar.ToString() },StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(parts[parts.Length - 1] + Path.DirectorySeparatorChar +
parts[parts.Length - 2]);
}
I would just remove anything before \MySite and get the rest:
Test data used:
List<string> source = new List<string>
{
#"\\Server\Site\MySite\File1.xml",
#"\\Server\Site\MySite\File2.xml",
#"\\Server\Site\MySite\File2.xml",
#"\\Server\Site\MySite\File10.xml",
};
query:
var result =
source
// Start removing at 0 and remove everything before '\MySite'
.Select(x => x.Remove(0, x.IndexOf("\\MySite")))
.ToList();
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.