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.*))");
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();
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 am reading a file that contains rows like
pathName; additionalString; maybeSomeNumbers
I read it using
var lines = File.ReadAllLines(fileListFile);
var fileListEntries = from line in lines
where !line.StartsWith("#")
select line.Split(';').ToArray();
This works well so far. However I would like to change the drive letter in the pathName. I could convert fileListEntries to an array and loop across elements [i][0], but is there a way that I could do this operation on the collection directly?
Use the LINQ extension method syntax in order to be able to use code blocks { ... } in the lambda expressions. If you do so, you have to include an explicit return-statement.
var fileListEntries = lines
.Where(l => !l.StartsWith("#"))
.Select(l => {
string[] columns = l.Split(';');
if (Path.IsPathRooted(column[0])) {
string root = Path.GetPathRoot(columns[0]);
columns[0] = Path.Combine(#"X:\", columns[0].Substring(root.Length));
}
return columns;
})
.ToArray();
I think you can do it inline with the LINQ.
File.ReadAllLines() returns a string array, so you should be able to perform Replace() on the line from the collection.
var replace = "The string to replace the drive letter";
var lines = File.ReadAllLines(fileListFile);
var fileListEntries = from line in lines
where !line.StartsWith("#")
select (line.Replace(line[0], replace).Split(';')).ToArray();
You could just call a method in your select that modifies the text in the manner that you would like.
static void Main(string[] args)
{
var fileListEntries = from line in lines
where !(line.StartsWith("#"))
select ( ModifyString(line));
}
private static string[] ModifyString(string line)
{
string[] elements = line.Split(';');
elements[0] = "modifiedString";
return elements;
}
lines.Where(l => !l.StartsWith("#").
Select(l => string.Concat(driveLetter, l.Substring(1))).
Select(l => l.Split(';');
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);