Have a string like A=B&C=D&E=F, how to remove C=D part and get the string like A=B&E=F?
Either just replace it away:
input.Replace("&C=D", "");
or use one of the solutions form your previous question, remove it from the data structure and join it back together.
Using my code:
var input = "A=B&C=D&E=F";
var output = input
.Split(new string[] {"&"}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=', 2))
.ToDictionary(d => d[0], d => d[1]);
output.Remove("C");
output.Select(kvp => kvp.Key + "=" + kvp.Value)
.Aggregate("", (s, t) => s + t + "&").TrimRight("&");
using System.Web; // for HttpUtility
NameValueCollection values = HttpUtility.ParseQueryString("A=B&C=D&E=F");
values.Remove("C");
values.ToString(); // "A=B&E=F"
I think you need to give a clearer example to make sure it's something for the situation, but something like this should do that:
var testString = "A=B&C=D&E=F"
var stringArray = testString.Split('&');
stringArray.Remove("C=D");
var output = String.Join("&", stringArray);
Something like that should work, and should be pretty dynamic
You can either split() and manually join (depending how the data looks like) or simly use string.Replace(,string.empty)
Split it on the & separator, exclude the C=D part by some mechanism, then join the remaining two? The String class provides the methods you'd need for that, including splitting, joining and substring matching.
string xyz = "A=B&C=D&E=F";
string output = xyz.Replace("&C=D","");
Output: A=B&E=F
Related
Please help on converting a list of objects got from DB into substrings separated by a comma
Take for example I have a sample code below:
List<string> CategoryNames = new List<string>();
CategoryNames.Add("myName1");
CategoryNames.Add("myName2");
CategoryNames.Add("myName3");
I want to convert CategoryNames into a format like this
"myName1","myName2","myName3"
From the above CatgoryNames happen to be retrieved from db.
var categoryNames = _context.BillingCategory.ToList();
How do I convert the categoryNames into substrings as shown above?
Any help will be appreciated.
You can use String.Join() method by combining with LINQ for preserving the quotes before joining:
var result = String.Join(",", CategoryNames.Select(item => $"\"{item}\""));
And here is the clearer version of the code if you don't linke singleliner:
var QuotedCategroyNames = CategoryNames
.Select(item => $"\"{item}\"");
var result = String.Join(",", QuotedCategroyNames);
Use LINQ Select to enclose all names in quotes, then string.Join to merge back into a comma separated string.
string.Join(',', CategoryNames.Select(n => '"' + n + '"'));
You can use string.Join() and concat with the double quotes character :
var serialized = $#"""{ string.Join(#""",""", CategoryNames) }"""; // "myName1","myName2","myName3"
Try it yourself
Consider the following csv
string data = "Hey, Bob, How are you";
I can flatten it to:
"Hey; Bob; How are you"
Using the following:
var s = String.Join("; ",data.Split(',').Select(d => d.Trim()).ToArray());
Is there any way I can get the index of the current item in the join and append it to the resulting string? To produce somthing along the lines of:
"Hey=0; Bob=1; How are you=2"
Does linq facilitate anything like this? Perhaps combined with a String.Format() type method?
Here try this there is an index selector in the select you can use it to concatonate with each of your data pieces
var s = String.Join("; ",data.Split(',')
.Select((d, i) => d.Trim() + "= " + i.ToString()).ToArray());
Sure - just change your Select slightly:
var s = String.Join("; ",data.Split(',')
.Select((d, i) => String.Format("{0}={1}",d.Trim(),i)));
note that string.Join can take an IEnumerable<T> so there's no need to call ToArray.
I have an array of words
string[] words = { "believe", "relief", "receipt", "field" };
How to find out the words with the substring "ei" using linq
IEnumerable<string> iswordlist = from word in words where words.All(a => a.Contains("ei"))
select word;
foreach (var i in iswordlist)
{
txtlinq.Text = txtlinq.Text + i.ToString();
}
I tried the above but got no result. Can anyone help me on this?
Try like this
var newWord = words.Where(o => o.Contains("ei"));
I'm not very good with free form, but with dot syntax this will work:
var ieWords = words.Where(a => a.Contains("ei"));
Your current code won't even compile because you are using Enumarbale.All method which returns either true or false (when given condition matches) and not an IEnumerable on which you can query. You simple need a Where clause.
Try this:-
var result = words.Where(x => x.Contains("ei"));
Or if you prefer query syntax:-
IEnumerable<string> result = from word in words
where word.Contains("ei")
select word;
Working Fiddle.
My values come from ComboBox:
2|722|742|762|77
I delete unnecessary characters as follows:
foreach (var item in checkListBox)
{
string[] list = item.Split(
new string[] { "2|" },
StringSplitOptions.RemoveEmptyEntries);
}
My list values result:
"72"
"74"
"76"
"77"
My question is:
how can I get all of the above values in 1 row (next to each other) separated by comma like this:
72,74,76,77
?
It sounds like you just want string.Join:
string commaSeparated = string.Join(",", list);
(Note that this is not part of LINQ - it's not the same kind of "join" as for joining multiple sequences. It's joining several strings together with a separator.)
While you can do this in a single statement as per the currently accepted answer, I'd personally consider leaving your existing statement and having this as a separate step. It makes the code easier to both read and debug.
String.Join(",",list);
Though: a) This is not Linq. b) As is mentioned in another answer here - It would be simpler in this case to use Replace.
Using Linq:
list.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(',');
How about
var result = string.Join(",", item.Split(new string[] { "2|" }, StringSplitOptions.RemoveEmptyEntries));
Just use Replace directly:
string input = "2|722|742|762|77";
var result = input.Replace("2|",",").Trim(',');
As noted in the other answers, string.Join is what should be used here. If you'd however insist on LINQ:
var result = list
.Skip(1)
.Aggregate(
list.FirstOrDefault() ?? string.Empty,
(total, current) => total + "," + current);
I have an issue with string manipulation in c#. Please check the follwoing expression :
public static string UNID = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier")).Value.Substring( //issue is here
I want to point the value in the substring function for applying the indexOf function on it. I tried this keyword but not working :
public static string UNID = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier")).Value.Substring(this.IndexOf('/') + 1);
I know that we can do the same thing by breaking the expression into parts like :
var value = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier")).Value;
var UNID = value.Substring(value.IndexOf('/') + 1);
But if there is any solution for this just like i was trying with this keyword. Then please let me know ?
Personally I think having it as two separate lines is the best way to do this, but if you are dead set on one line you can use Split instead. The second parameter indicates that you only want to split on the first delimiter.
var UNID = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity)
.Claims.Single(c => c.ClaimType.Contains("nameidentifier"))
.Value.Split(new[] {'/'}, 2)[1];
This should work:
public static string UNID = ((Thread.CurrentPrincipal as ClaimsPrincipal).Identity as ClaimsIdentity).Claims
.Where(c => c.ClaimType.Contains("nameidentifier"))
.Select(c => c.Value.Substring(c.Value.IndexOf('/')+1))
.Single();
first select the requested claimtype
then convert that to the correct value-substring
and take the only (expected) value