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;
Related
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.*))");
I'm new to linq. I have a string having the following format
code:description;code2:description2;code3:description3... etc.
Records are separated with ; character and each record has 2 fields separated with : character.
I'm writing a linq query to extract a list of objects having as fields code and description.
I have written the following query which seems to produce correct results, but I was wondering if there is a better or more correct way to do it.
var objects =
from objString in recsString.Split(';')
let obj = objString.Split(':')
select new {
Code = obj[0].Trim(),
Description = obj[1].Trim()
};
That's perfectly fine, the only observation I would make though is that you remove empty entries by using the StringSplitOptions:
var objects =
from objString in recsString.Split(';', StringSplitOptions.RemoveEmptyEntries)
let obj = objString.Split(':', StringSplitOptions.RemoveEmptyEntries)
select new {
Code = obj[0].Trim(),
Description = obj[1].Trim()
};
If you think that there could be missing information, you could also be extra safe and null check the results:
var objects =
from objString in recsString.Split(';', StringSplitOptions.RemoveEmptyEntries)
let obj = objString.Split(':', StringSplitOptions.RemoveEmptyEntries)
select new {
Code = obj.Any() ? obj[0].Trim() : string.Empty,
Description = obj.Count > 1 ? obj[1].Trim() : string.Empty
};
What you're doing is just fine, here is how you'd write it using lambdas:
string objString = "code:description;code2:description2;code3:description3";
Dictionary<string, string> results =
objString.Split(';')
.Select(x => x.Split(':'))
.ToDictionary(key => key[0], value => value[1]);
// And now you have a nice little dictionary
foreach (var r in results)
Console.WriteLine("{0}:{1}",r.Key, r.Value);
Or of course:
var results = objString.Split(';')
.Select(x => x.Split(':'))
.Select(x => new {Code = x[0], Description = x[1]});
foreach (var r in results)
Console.WriteLine("{0}:{1}",r.Code, r.Description);
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);
Given a list of strings like this
"Val.1.ValueA"
"Val.1.ValueB"
"Val.1.ValueC"
"Val.2.ValueA"
"Val.2.ValueB"
"Val.2.ValueC"
"Val.3.ValueA"
"Val.3.ValueB"
"Val.3.ValueC"
How can I write a linq groupby statement to group by the first part of the string including the number? In other words, in the above case I want a list of 3 groups Val.1, Val.2, Val.3
Use String.Split() to define your group key:
var groups = myList.GroupBy(x => { var parts = x.Split('.');
return parts[0] + parts[1]; });
This would work regardless of the length of both parts of the key (before and after the dot).
Edit in response to comment:
It sounds like you want to group by a number within the string, but you do not know in advance which part constitutes the number. In this case this should work:
var groups = myList.GroupBy(x =>
{
var parts = x.Split('.'));
int num = 0;
return parts[0] + parts.Where(p => p.All(char.IsDigit)
.First( p => int.TryParse(p, out num));
}
);
Without more information about the formatting, the simplest is:
var groups = list.GroupBy(s => s.Substring(0, 5));
If these are in fact not fixed length:
var groups = list.GroupBy(s => {
var fields = s.Split('.');
return String.Format("{0}.{1}", fields[0], fields[1]);
});
I have to search a list of strings in CityList and if it contains all search strings
then it should return true otherwise false.
When i search "London","Dallas" against CityList it should return false,because
"Dallas" is missing in CityList.
var CityList=new string[] { "London","Paris","Houston","Mexico","Budapest"}
var search =new string[] {"London","Dallas"};
How to rewrite the following ?
var result = CityList.Select(c => c).ToList().FindAll(search.ToArray());
Try the following:
var hasAll = !search.Except(CityList).Any();
By the way, you should never write something.Select(c => c); such a statement will do nothing but make the program a tiny bit slower.
Try this:
var result = search.All(s => CityList.Contains(s));
You have various possibilities:
var result = CityList.Union(search).Count() == CityList.Count();
var result2 = search.All(s => CityList.Contains(s));
var result3 = search.ToList().TrueForAll(s => CityList.Contains(s));
var result4 = CityList.Intersect(search).Count() == search.Count();
That quite an easy one
search.All(c => CityList.Contains(c))
All will only satify when all predicates return true, then we check if the citylist contains the item