I have a C# list full of strings.
I would like to exclude those items that match a specific pattern like those strings that start with "DST*"
Any string that doesn't start with DST, am happy to take, but anything that starts with DST I would like to remove from this list.
I see linq has Contains(). But how do I do the inverse of Contains()?
You can use the ! operator to inverse any bool:
var filtered = listOfStrings.Where(x => !x.StartsWith("DST"));
anything that starts with DST I would like to remove from this list.
You don't need LINQ you could also use List<T>.RemoveAll:
listOfStrings.RemoveAll(s => s.StartsWith("DST"));
But of course this modifies the original list and does not create a new. If that's desired use the approach from Somebody.
Related
What is the best practice way to use two clauses in LINQ Contains method..
Title is string
This is my If statement :
if (oWeb.ParentWeb.Title.Contains("Ricky") || oWeb.ParentWeb.Title.Contains("John"))
I need solution like this :
if (oWeb.ParentWeb.Title.Contains("Ricky", "John"))
Since Title is string this actually has nothing to do with LINQ as the used Contains method is an instance method of string.
Assuming you have more strings to check, you can do something like that:
var strings = new[] {"Ricky", "John"};
if (strings.Any(oWeb.ParentWeb.Title.Contains))
// do something
But roryap's answer using a regex seems preferable (as long as the number of strings to check is not too big).
I don't think LINQ is the best option for that. Why not use regular expressions?
Regex.IsMatch(oWeb.ParentWeb.Title, "ricky|john", RegexOptions.IgnoreCase);
Contains takes only one parameter, so you cannot do it this way.
You can make an array of items, and check containment with it:
var titles = new[] {"Ricky", "John"};
if (titles.Any(t => oWeb.ParentWeb.Title.Contains(t))) {
...
}
I have a list of objects, and i need to filter that objects that one of his properties DONT start with some letter, i see that i can do it:
onelist=mylist.where(x=>x.Cod.startwith("A"));
but what i need is just the contrary, something like:
onelist=mylist.where(x=>x.Cod.NOTstartwith("A"));
I dont know if it´s posible, if that it´s not posible i seem to remember that there was a way to in one lamda expression negate other, is correct??
Thanks
Just use standard boolean operator:
onelist = mylist.Where(x => !x.Cod.StartsWith("A"));
I have this case:
I create an array from a list like this:
String[] parameters = stringParametersToSearch.Split(' ');
The number of parameters can vary from 1 to n and I have to search for objects that in the description field containing all the occurrences of parameters
List<LookUpObject> result =
components.Where(o => o.LongDescription.Contains(parameters[0])).ToList<LookUpObject>();
if the parameter is 1 do so, but if they had two or more?
Currently to resolve this situation, I use an IF in which I build the LINQ expression for cases up to five parameters (maximum of real cases).
I can resolve this situation dynamically using LINQ ?
You either want to use Any or All, depending on whether you want to find objects where all of the parameters match or any of them. So something like:
var result = components
.Where(o => parameters.Any(p => o.LongDescription.Contains(p)))
.ToList();
... but change Any to All if you need to.
It's always worth trying to describe a query in words, and then look at the words you've used. If you use the word "any" or "all" that's a good hint that you might want to use it in the query.
Having said that, given the example you posted (in a now-deleted comment), it's not clear that you really want to use string operations for this. If the long description is:
KW=50 CO2=69 KG=100
... then you'd end up matching on "G=100" or "KG=1" neither of which is what you really want, I suspect. You should probably parse the long description and parameters into name/value pairs, and look for those in the query.
In my LINQ to Entities query I have a .orderby f.Description.Trim() command
The reason for .Trim() is that some of the data coming from DB have a bunch of white spaces at the beginning of them so I wanted to trim those so they won't affect sorting.
Now it sorts correctly but I see something like this in the result:
[Queries - Blah]
Action
Adhere
Azalia
Then I looked up ASCII code of "[" and it is 91 and "A" is 65 so how come that one showed up first? Maybe there are some other things in the code causing this and sort is fine?
OrderBy is using the default comparator for strings, which doesn't use ASCII (actually, Unicode) ordinal comparison. It actually depends on the current culture you are using.
And, if you think about it... if you were sorting entries for an appendix or index, symbols come before letters (at least in English).
If you want to sort by "raw ascii value", use
...OrderBy(s => s, StringComparer.Ordinal)
If the actual expression can be compiled to a store expression, then the ordering will be done as implemented by your store.
So: the result will depend on the collation of the database, table and column.
I have this code :
stringCutted = myString.Split("/"). // ???
and I'd like to store in stringCutted the last element of the string[] after the split, directly, quickly, without storing the splitted array in a variable and access to that element with array[array.length].
Is this possible in C#?
If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:
stringCutted = myString.Split('/').Last();
Note that Last() (without a predicate) is optimized for the case where the source implements IList<T> (as a single-dimensional array does) so this won't iterate over the whole array to find the last element. On the other hand, that optimization is undocumented...
stringCutted=myString.Split("/").Last()
But, just FYI, if you're trying to get a filename from a path, this works heaps better:
var fileName=System.IO.Path.GetFileName("C:\\some\path\and\filename.txt");
// yields: filename.txt
Since you want a solution that returns the last element directly, quickly, without store the splitted array, i think this may be useful:
stringCutted = myString.Substring(myString.LastIndexOf("/")+1);
Use LINQ
"t/e/s/t".Split("/").Last();
For using this code, I skip last element from the Url link.
string url = Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf('/'));
For Addition:
When string format like 'a/b/c/d' then
yourstring.Split("/").Last();
When string format like \head_display\27_[Item A]\head_image\original_image\1_Item A.png
yourstring.Split("\\").Last();
first '\' actually to skip second '\'