I have a array of strings . I need to check in the array if it has something like "abcd". How to achive this in C#. I tried using the
var pathBits = new[] {"abcde ","abcd &"};
var item ="abcd";
var results = Array.FindAll(pathBits, s => s.Equals(item ));
maybe something like this:
var result = pathBits.Any(y => y.Contains(item));
That will give you true if the array contains an item that has a value like item. If you want to select all those values you should use:
var result = pathBits.Where(y => y.Contains(item));
which will give you an IEnumerable of the items from the list that contain the value item.
When you say 'something like "abcd"' do you mean "Starts with" or "Contains"?
The current code will only find strings in pathBits which are exactly equal to item ("abcd" ?)
The general shape is fine but to find non-exact matches you need to change the predicate
e.g.
string[] src = new[] { "abcde", "abcd &" };
var results = Array.FindAll<string>(src, name => name.Contains("abcd"));
This can also be implemented using the Linq IEnumerable<> extensions
e.g.
string[] src = new[] { "abcde", "abcd &" };
var results = src.Where(name => name.Contains("abcd"));
hth,
Alan.
This might be of some use
string[] pathBits = { "abcde ", "abcd &" };
var item = "abcd";
if (pathBits.Contains(item)) ;
{
}
You cannot use
var pathbits = { "abcde ", "abcd &" };
Please let me know if you have any problem
Is this what your looking for?
string[] pathBits = { "abcde ", "abcd &", "222" };
var item = "abcd";
var results = Array.FindAll<string>(pathBits, s => s.Contains(item));
results will have 2 items.
I'm not sure exactly what you want, but this would get all array allements that contain the string "abcd" -
String[] pathBits = {"abcde ","abcd &"};
var item ="abcd";
var results = pathBits.Where(s => s.IndexOf("abcd") > -1);
Related
From a given list of strings I need to use LINQ to generate a new sequence of strings, where each string consists of the first and last characters of the corresponding string in the original list.
Example:
stringList: new[] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" },
expected: new[] { "ee", "fg", "jw" });
list2 = stringList.Select(e => {e = "" + e[0] + e[e.Length - 1]; return e; }).ToList();
This is what I've tried, it works, but I need to use LINQ to solve the problem and I'm not sure how to adapt my solution.
just for the sake of completeness here is a version using Zip
var stringList = new string [] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" };
var result = stringList.Zip(stringList, (first, last) => $"{first.First()}{last.Last()}");
As mentioned in the comment that Select is already part of LINQ, you can use this code.var output = arr.Select(x => new string(new char[] { x.First(), x.Last() })).ToList();
Here you go:
var newList = stringList.Select(e => $"{e[0]}{e[e.Length - 1]}").ToList();
Approach with LINQ and String.Remove():
string[] input = new[] { "ehgrtthrehrehrehre", "fjjgoerugrjgrehg", "jgnjirgbrnigeheruwqqeughweirjewew" };
string[] result = input.Select(x => x.Remove(1, x.Length - 2)).ToArray();
If I filter a list for multiple criteria I can do this like this:
string[] criteria = { "a1", "b1" };
var res = reslist.Where(x => criteria.Contains(x.book)).ToList();
Now I would like to do sth like this:
string[] criteria = { "a", "b" };
var res = reslist.Where(x => criteria.ContainsStartsWith(x.book)).ToList();
Obviously this doesnt exists. How can I check through a criteria list with startswith values?
You could use Any extension method .
var res = reslist.Where(x => criteria.Any(s=>s.StartsWith(x.book)).ToList();
Minor add to Hari's answer
Use below
var res = reslist.Where(x => criteria.Any(s=>s.StartsWith(x.book) || criteria.Contains(x.book)).ToList();
I have a string[] containing ie:
abcd
Saving C:\\xx
aacd
Saving C:\\yy
aecd
Saving C:\\zz
and so on
Is there a way in linq that searches all the lines and returns only C:\\xx, C:\\yy and C:\\zz to a list/array.
This is what i tried so far:
string[] line = result.Split(new[] { '\r', '\n' });
string searchTerms = "Saving ";
var results = (from comp in line.ToString()
where searchTerms.All(s => comp.Contains(s))
select comp).ToList();
You don't need All method, you can just use:
where comp.StartsWith(searchTerms)
And instead of splitting on \r and \n it's better to use:
string[] line = result.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
And you should also remove ToString from line.ToString()
var results = (from comp in line
where comp.StartsWith(searchTerms)
select comp).ToList();
I don't, really understand your kind of input data, but if it is like this
string[] str = new string[] { "abcd", "Saving C:\\xx", "aacd", "Saving C:\\yy", "aecd", "Saving C:\\zz"};
then you can do the following:
List<string> result = str.Where(s => s.StartsWith("Saving C:\\")).ToList();
If string ends path:
string result = #"abcd
Saving C:\xx
aacd
Saving C:\yy
aecd
Saving C:\zz
and so on";
string[] line = result.Split(new[] { '\r', '\n' });
string searchTerms = "Saving ";
var lst = line.Where(x => x.StartsWith(searchTerms))
.Select(y => y.Substring(searchTerms.Length));
foreach (var x in lst)
Console.WriteLine(x);
http://ideone.com/OXDMO5
This should give you a simple IEnumerable containing each path.
NOTE: This will only return the part of each line after whatever is in searchTerms.
var result =
line.Where(l => l.StartsWith(searchTerms))
.Select(c => new string(c.Skip(searchTerms.Count()).ToArray()));
If all you want to do is get the paths from a string you can use regular expressions for this:
var result = "abcd\r\nSaving C:\\xx\r\naacd\r\nSaving C:\\yy\r\naecd\r\nSaving C:\\zz\r\n";
var regex = new Regex(#"(?<=Saving )(.*)");
var matches = regex.Matches(result).Cast<Match>().Select(m => m).ToList();
Edit
Another more generic form of regular expression you can use to get all paths (not just the ones with Savingbefore them):
var matches = Regex.Matches(result, ".:\\\\(.*?)(?=\s.*)", RegexOptions.Multiline).Cast<Match>().Select(m => m).ToList();
This also removes any whitespace after the paths.
Edit 2
To also get paths within quotes (paths with spaces) you can use this regular expression:
var regex = new Regex("((\"\\w|\\w):\\\\)((.*\")|(.*?)(?=\\s.*))");
Hi I am looking for a simple way to et just the name after the CN value
CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net
is there an easy way to do this? I am currently doing this:
ResultPropertyValueCollection manager = result.Properties["manager"];
string managerUserName = manager[0].ToString();
string[] managerNameParts = managerUserName.Split(',');
string managerName = managerNameParts[0].Substring(4);
Console.WriteLine("Manager Name:" + managerName);
but it feels kind of bad.
This is a great place to use Regular Expressions. Try this:
var text = "CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net";
var match = Regex.Match(text, #"CN=([^,]+)");
if (match.Success) return match.Groups[0].Value;
The expression CN=([^,]+) will look for the text CN= followed by one or more non-commas, and will stick that part of it into Groups[0].
You can do this:
var name = "CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net"
.Split(',')[0].Split('=')[1];
Demo
What it does is splits on , and takes the first element and then splits it by = and takes the second element.
If you cannot have the same format, you can do a regex:
Regex.Match(name,#"(?<=CN=)[^,]+").Value;
Another option, using LINQ.
If the name/value pair exists anywhere in the string, you'll get it; if not, managerName will be null.
var managerName = input.Split(',')
.Where(x => x.StartsWith("CN="))
.Select(x => x.Split('=')[1])
.SingleOrDefault();
I find doing it like this fairly easy to read:
var input = #"CN=Andrew Adams,OU=Services,OU=Users,OU=GIE,OU=CSP,OU=STAFF,DC=example,DC=net";
var items = input.Split(',');
var keyValues = items.Select(x =>
{
var split = x.Split('=');
return new { Key = split[0], Value = split[1] };
});
var managerName = keyValues.Single(x => x.Key == "CN").Value;
I have a List<List<string>> and when I try to search with the List<string> it returns no results.
Any ideas?
Thanks
List<List<string>> test = new List<List<string>>();
List<string> ff = new List<string>();
ff.Add("1");
ff.Add("ABC 1");
test.Add(ff);
ff = new List<string>();
ff.Add("2");
ff.Add("ABC 2");
test.Add(ff);
var result = test.Where(x=>x.Contains("ABC"));
//result.Count(); is 0
Neither of your lists contains the element "ABC".
If you want to find the lists that have an element that contains "ABC" as a substring you can do this:
var result = test.Where(x => x.Any(y => y.Contains("ABC")));
Its because you are doing a list of a list and not going far enough down in your selection. Something like this should give you two results:
var result = test.Select(x => x.Where(y => y.Contains("ABC")));
none of your lists contain the string "ABC". It doesn't search the string when you use that contains function, it just matches the whole string. If you want to search for a partial string, then you have to use something like the following:
var result = test.Where(x => x.Where(y => y.Contains("ABC").Count() > 0));