I am trying to split this string
string s = "sn DC0000002; mac 00:0c; uuid 564d6ae4-979";
I need to get these values from above string "DC0000002" , "00:0c" , "564d6ae4-979"
For this I have tried below query but not able to able to get last two values I mean these two values ("00:0c" , "564d6ae4-979")
Below is the query for splitting
List<string> decryptedList = new List<string>();
decryptedList = decodePP.Split(';').Select(x => x.Split(' ')[1]).ToList();
orgSNo = decryptedList[0]; //Output - DC0000002
orgMacID = decryptedList[1];// output - mac // this is wrong need to get value
orgUUID = decryptedList[2]; //output - uuid // this is also wrong
Would anyone please help on this query how extract values from the above string using LINQ query in a single shot?
Just trim substrings which you get after first split:
decodePP.Split(';').Select(x => x.Trim().Split(' ')[1]).ToList();
You get incorrect results, because first split gives you
[ "sn DC0000002", " mac 00:0c", " uuid 564d6ae4-979" ]
As you can see, items except first one have leading whitespace.
Alternative solution - you can use StringSplitOptions.RemoveEmptyEntries parameter to skip empty substrings
str.Split(';')
.Select(x => x.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1])
.ToList()
Why do you need to use Linq. The string split would seem to do the trick?
string[] keyValuePairs = s.Split(';');
foreach(string pair.Trim() in keyValuePairs)
{
string key = pair.Split(' ')[0].Trim();
string value = pair.Split(' ')[1].Trim();
}
That's only a stab at the code - it may not compile, but you get the idea?
You could use the TrimStart() function in your linq statement like:
decryptedList = decodePP.Split(';').Select(x => x.TrimStart().Split(' ')[1]).ToList();
Related
I have this code that splits a specific string.
str = "\n\nThis\nString\nis\nsplit\ninto\narray";
string[] delimiterChar = { "\n" };
var splitArray = str.Split(delimiterChar);
The split array is simple array of strings, but why isn't it possible to remove the first 2 item by using:
splitArray[0].remove();
splitArray[0].remove();
If you need to remove empty entries, then just specify it in the split method. There is no need to remove them manually.
var splitArray = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries);
If you want to specifically remove certain specific elements, then you can convert the array (non-mutable) to a list (mutable), and work on it like:
var splitList = str.Split(delimiterChar, StringSplitOptions.RemoveEmptyEntries).ToList();
splitList.RemoveAt(0);
This might be one of the solution which might get the desired result.
string str = "\n\nThis\nString\nis\nsplit\ninto\narray";
str = str.TrimStart('\n');
var splitArray = str.Split('\n');
yes,but sometimes the string contains random string at the first 3 indexes..
so i want to split this simple string into Array via Split and remove .
The split array is simple array of strings, but why isn't it possible to remove the first 2 items
Split it and then skip whatever number of items you wish using Linq:
// I am skipping 3 for example
var splitArray = str.Split(delimiterChar).Skip(3).ToList();
Make sure to add this to the list of using statements:
using System.Linq;
I have a comma separated string stored in database.
E.g.: record1 = "1,3,5,7,9,10" and record2 = "4,5,10"
And I have a given information, E.g.: 1.
I have to select the record using LINQ that contains the given info of 1.
The result returned should be record1.
If I were to use .contains() solely, it's not accurate as record2 will be returned as well.
How can I achieve that? Is it possible to achieve that in a single LINQ query?
Thanks for advise !
With a single LINQ-to-objects query:
string[] records = new[] { record1, record2 };
string record = records.FirstOrDefault(r => r.Split(',').Any(s => s == "1"));
Demo
First of all I would like to mention what #Tim Schmelter said -
Have you noticed already that the real problem is your creepy
datamodel? Use a table with real records instead of a column with a
comma separated string.
It is not a good practice to use a datamodel where you need string split match. Because it leads to inefficient systems and not to mention slow queries. But yet, if you really need a solution why not try this -.
There are four occasions where you will get a match,
A prefix match - starting with
Inner Match - contains with
Suffix Match - ends with
The only match - only one item and this is it
considering the scenario I am suggesting the solution below -
s is the value looking for say "1"
string prefixMatch = s + ",";
string suffixMatch = "," + s;
string innerMatch = "," + s + ",";
string record = <dbRecords>.FirstOrDefault(r=> r.StartsWith(prefixMatch) ||
r.Contains(innerMatch) || r.EndsWith(suffixMatch) ||
(!r.Contains(",") && r == s));
The reason for such a detailed query is to keep your memory utilisation less and letting the SQL query do the hard work of finding the results because this query will support LINQ-to-SQL conversion.
If i understand you correctly, you need as result record that contains "1". So you can use:
private bool GerRecord(string record)
{
string[] arr=record.Split(',');
return arr.Contains("1");
}
Instead of searching 1 you can try 1,(1 and comma combined) for searching in Contains in linQ
I have the following text in a file:
"SHOP_ORDER001","SHOP_ORDER002","SHOP_ORDER003","SHOP_ORDER004","SHOP_ORDER005"
Now I am getting the values by reading the file and assigning to array by spilt:
String orderValue = "";
string[] orderArray;
orderValue = File.ReadAllText(#"C:\File.txt");
orderArray = orderValue.Split(',');
But I am getting the values as :
I need the Values in Array as "ORDER001","ORDER002","ORDER003"
The \" you see is just added by debugger visualizer for strings (because quote is a special characted and need to be escaped to don't get confused), don't worry they're not in your orderArray.
In case you want to remove quotes too so that your array will be:
SHOP_ORDER001
SHOP_ORDER002
...
Just use this (with LINQ):
var orderArray = orderValue.Split(',').Select(x => x.Trim('"'));
By the way String.Split isn't very robust unless you're sure each field will never contain a comma.
EDIT
To answer the point you added in the comments if you need to remove SHOP_ just write this:
var orderArray = orderValue.Split(',')
.Select(x => x.Trim('"').Substring("SHOP_".Length));
use this regex
var res = Regex.Matches(orderValue, #"(?<=""SHOP_)[^""]+?(?="")");
You could use this:
string[] result = Regex.Split(orderValue, "(?:^\"SHOP_)|(?:\",\"SHOP_)|(?:\"$)");
However you will have to skip the first and last items in the resulting array as they will always be empty strings.
Silly question but why don't you just do
.Replace("SHOP_", "");
What i'm trying to do is split a string backwards. Meaning right to left.
string startingString = "<span class=\"address\">Hoopeston,, IL 60942</span><br>"
What I would do normally is this.
string[] splitStarting = startingString.Split('>');
so my splitStarting[1] would = "Hoopeston,, IL 60942</span"
then I would do
string[] splitAgain = splitStarting[1].Split('<');
so splitAgain[0] would = "Hoopeston,, IL 60942"
Now this is what I want to do, I want to split by ' ' (a space) reversed for the last 2 instances of ' '.
For example my array would come back like so:
[0]="60942"
[1]="IL"
[2] = "Hoopeston,,"
To make this even harder I only ever want the first two reverse splits, so normally I would do something like this
string[] splitCity,Zip = splitAgain[0].Split(new char[] { ' ' }, 3);
but how would you do that backwards? The reason for that is, is because it could be a two name city so an extra ' ' would break the city name.
Regular expression with named groups to make things so much simpler. No need to reverse strings. Just pluck out what you want.
var pattern = #">(?<city>.*) (?<state>.*) (?<zip>.*?)<";
var expression = new Regex(pattern);
Match m = expression .Match(startingString);
if(m.success){
Console.WriteLine("Zip: " + m.Groups["zip"].Value);
Console.WriteLine("State: " + m.Groups["state"].Value);
Console.WriteLine("City: " + m.Groups["city"].Value);
}
Should give the following results:
Found 1 match:
1. >Las Vegas,, IL 60942< has 3 groups:
1. Las Vegas,, (city)
2. IL (state)
3. 60942 (zip)
String literals for use in programs:
C#
#">(?<city>.*) (?<state>.*) (?<zip>.*?)<"
One possible solution - not optimal but easy to code - is to reverse the string, then to split that string using the "normal" function, then to reverse each of the individual split parts.
Another possible solution is to use regular expressions instead.
I think you should do it like this:
var s = splitAgain[0];
var zipCodeStart = s.LastIndexOf(' ');
var zipCode = s.Substring(zipCodeStart + 1);
s = s.Substring(0, zipCodeStart);
var stateStart = s.LastIndexOf(' ');
var state = s.Substring(stateStart + 1);
var city = s.Substring(0, stateStart );
var result = new [] {zipCode, state, city};
Result will contain what you requested.
If Split could do everything there would be so many overloads that it would become confusing.
Don't use split, just custom code it with substrings and lastIndexOf.
string str = "Hoopeston,, IL 60942";
string[] parts = new string[3];
int place = str.LastIndexOf(' ');
parts[0] = str.Substring(place+1);
int place2 = str.LastIndexOf(' ',place-1);
parts[1] = str.Substring(place2 + 1, place - place2 -1);
parts[2] = str.Substring(0, place2);
You can use a regular expression to get the three parts of the string inside the tag, and use LINQ extensions to get the strings in the right order.
Example:
string startingString = "<span class=\"address\">East St Louis,, IL 60942</span><br>";
string[] city =
Regex.Match(startingString, #"^.+>(.+) (\S+) (\S+?)<.+$")
.Groups.Cast<Group>().Skip(1)
.Select(g => g.Value)
.Reverse().ToArray();
Console.WriteLine(city[0]);
Console.WriteLine(city[1]);
Console.WriteLine(city[2]);
Output:
60942
IL
East St Louis,,
How about
using System.Linq
...
splitAgain[0].Split(' ').Reverse().ToArray()
-edit-
ok missed the last part about multi word cites, you can still use linq though:
splitAgain[0].Split(' ').Reverse().Take(2).ToArray()
would get you the
[0]="60942"
[1]="IL"
The city would not be included here though, you could still do the whole thing in one statement but it would be a little messy:
var elements = splitAgain[0].Split(' ');
var result = elements
.Reverse()
.Take(2)
.Concat( new[ ] { String.Join( " " , elements.Take( elements.Length - 2 ).ToArray( ) ) } )
.ToArray();
So we're
Splitting the string,
Reversing it,
Taking the two first elements (the last two originally)
Then we make a new array with a single string element, and make that string from the original array of elements minus the last 2 elements (Zip and postal code)
As i said, a litle messy, but it will get you the array you want. if you dont need it to be an array of that format you could obviously simplfy the above code a little bit.
you could also do:
var result = new[ ]{
elements[elements.Length - 1], //last element
elements[elements.Length - 2], //second to last
String.Join( " " , elements.Take( elements.Length - 2 ).ToArray( ) ) //rebuild original string - 2 last elements
};
At first I thought you should use Array.Reverse() method, but I see now that it is the splitting on the ' ' (space) that is the issue.
Your first value could have a space in it (ie "New York"), so you dont want to split on spaces.
If you know the string is only ever going to have 3 values in it, then you could use String.LastIndexOf(" ") and then use String.SubString() to trim that off and then do the same again to find the middle value and then you will be left with the first value, with or without spaces.
Was facing similar issue with audio FileName conventions.
Followed this way: String to Array conversion, reverse and split, and reverse each part back to normal.
char[] addressInCharArray = fullAddress.ToCharArray();
Array.Reverse(addressInCharArray);
string[] parts = (new string(addressInCharArray)).Split(new char[] { ' ' }, 3);
string[] subAddress = new string[parts.Length];
int j = 0;
foreach (string part in parts)
{
addressInCharArray = part.ToCharArray();
Array.Reverse(addressInCharArray);
subAddress[j++] = new string(addressInCharArray);
}
I have list of strings. I want to convert each element of it to single quoted string (i.e "ABC" --> 'ABC'), How to do this in .net.
Thanks,
Omkar
Linq can help here.
var newList = oldList.Select(c => c.Replace("\"", "'"));
This is already well answered. However, I have the hunch that you are taking a list of strings in C#, then trying to build an SQL expression for use in IN statements, e.g.:
SELECT * FROM table WHERE name IN ('John','Mary','Peter')
In that case, you'd need to join the strings together, as well as protect from code injection attacks by doubling any single-quote characters.
StringBuilder sb = new StringBuilder();
foreach (string entry in list) {
if (sb.Length > 0) sb.Append(",");
sb.Append("\'" + entry.Replace("'","''") + "\'");
}
string expr = sb.ToString();
You'd also need to handle the special case when the list is empty because IN () is not a valid syntax for SQL.
If this is not what you want, just ignore me. :-)
I assume you have regular strings s to 's' (quoted string) and you wanted a List<> to be converted.
List<string> stringList = new List<string>();
//Fill the list with strings here.
var query = from str in stringList
select string.Format("\'{0}\'", str);
List<string> quotedList = query.ToList<string>();
If you want to replace all double with single quotes, simply do this:
myString = myString.Replace( "\"", "'" );
However, note that ' is not a valid string delimiter in C#, so you can't have the string 'ABC', but you can have the string "'ABC'" that contains the text 'ABC'
EDIT
When looking at Geoff's answer, I saw that you wanted a list. In that case, his answer is almost correct- Try this variant instead:
var convertedList = myStringList.Select(s => s = s.Replace("\"", "'").ToList();