i need to find out a string from collection of strings using its sub string. This sub string
must be in starting.
collection.FirstOrDefault(s => s.StartsWith(whatever))
you can do something like this,
List<string> collection = new List<string>();
collection.Add("example sample");
collection.Add("sample");
collection.Add("example");
var varSubstring = collection.Where(x => x.IndexOf("sample")==0).ToList();
foreach (var vartemp in varSubstring)
{
}
Related
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) ;
}
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.
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'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.
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);