remove quote from list<string> using linq - c#

I have a List strings and each value has a leading quote that needs to be removed. Now there could be quotes further down the string and those will need to stay.
List<string> strings = new List<string>();
strings.Add("'Value1");
strings.Add("'Values2 This 2nd ' should stay");
Is there a linq way?

strings = strings.Select(x => x.StartsWith("'") ? x.Substring(1) : x).ToList();

strings.Select(s => s.StartsWith("'") ? s.Substring(1) : s);

var result = strings.Select(s => s.TrimStart('\''));
Note: This will remove all leading occurrences of ('). However, I assume that you will not have a string like "''Value1".

LINQ is really unnecessary for this. You could just use TrimStart() by itself:
strings.Add("'Value1".TrimStart('\''));

strings.ForEach(s => s = s.TrimStart('\''));
EDIT by Olivier Jacot-Descombes (it demonstrates that this solution does not work):
List<string> strings = new List<string>();
strings.Add("'Value1");
strings.Add("'Values2 This 2nd ' should stay");
Console.WriteLine("Before:");
foreach (string s in strings) {
Console.WriteLine(s);
}
strings.ForEach(s => s = s.TrimStart('\''));
Console.WriteLine();
Console.WriteLine("After:");
foreach (string s in strings) {
Console.WriteLine(s);
}
Console.ReadKey();
This produces the following output on the console:
Before:
'Value1
'Values2 This 2nd ' should stay
After:
'Value1
'Values2 This 2nd ' should stay

Related

How to use the trim function to trim inside of a list

I am trying to trim an item called Input (object form .json file) which is inside of a foreach loop.
The code I have at the moment is:
List<string> dhurl = new List<string>();
foreach (JObject item in jArray)
{
dhurl.Add("https://" + (string)item.SelectToken("Input");
}
input adds "sm-tiktoktrends.com", I want it to only add "tiktoktrends.com", how can I use trim to remove "sm-"?
*To clarify all Input objects will need sm- removed
The question is not clear if all values start with "sm-". If so, and you're willing to use LINQ:
List<string> dhurl = jArray.Select(item => "https://" + ((string)item.SelectToken("Input")).Substring(3)).ToList();
Otherwise, I might do it something like this:
List<string> dhurl = jArray
.Select(item => (string)item.SelectToken("Input"))
.Select(item => "https://" + (item.StartsWith("sm-") ? item.Substring(3) : item))
.LoList();
New example based on comment below:
List<string> dhurl = jArray
.Select(item =>
string.Format(
"https://{0}/?sig={1}",
((string)item.SelectToken("Input")).Substring(3),
(string)item.SelectToken("Signature")
))
.LoList();
You, probably, should use Substring(...) together with StartsWith(...) instead of Trim(...):
string input = item.SelectToken("Input").ToString();
if (input.StartsWith("sm-"))
{
input = input.Substring(3);
}
dhurl.Add("https://" + input);
dhurl.Add($"https://{item.SelectToken("Input").Replace("sm-","")}") ?

Output string after certain character is met

so what im doing currently is
getting the text from a file i.e a .txt
and putting it into an array i.e
whilst comparing the two files and outputting the differences between a and B
string[] linesA = File.ReadAllLines(path\file.txt);
string[] linesB = File.ReadAllLines(path\file2.txt);
IEnumerable<String> onlyB = linesB.Except(linesA);
string[] newstr = new HashSet<string>(onlyB).ToArray();
File.WriteAllLines('C:\path\', newstr);
and lets say the text inside the files includes : i.e
file a:
code(324332): 65dfsdf4fth
code(32342): hdfgvsdfsdgh
code(323462): h29dfs8dh
file b:
code(324332): 65dfsdf4fth
code(32342): hdfgvsdfsdgh
code(323462): h29dfs8dh
code(453453): 8gbhfhk,jv
code(343435): gigdbioyvgi
code(3435343): guidfyvfhs
how would i go about getting the text after :
and removing duplicates
so in the end the output would be
8gbhfhk,jv
gigdbioyvgi
guidfyvfhs
edited:
Kind regards,
Phil
You can browse files and registrars row by row in a list of type "Dictionary .Add (TKey, TValue)" so that you only have the unique values.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.add?view=netframework-4.8
To get the text after : you can use the Substring and IndexOf methods, then remove the whitespace at the beginning of your new string with TrimStart. At the end use Concat to combine the two lists and GroupBy to filter out the values that have duplicates:
string[] linesA = File.ReadAllLines(#"C:\file.txt");
string[] linesB = File.ReadAllLines(#"C:\file2.txt");
IEnumerable<string> linesA2 = linesA.Select(x => x.Substring(x.IndexOf(":") + 1).TrimStart());
IEnumerable<string> linesB2 = linesB.Select(x => x.Substring(x.IndexOf(":") + 1).TrimStart());
string[] result = linesA2.Concat(linesB2).GroupBy(x => x)
.Where(g => g.Count() == 1)
.Select(y => y.Key)
.ToArray();
result:
result[0] ="8gbhfhk,jv"
result[1] ="gigdbioyvgi"
result[2] ="guidfyvfhs"
Write the result array to new text file:
File.WriteAllLines(#"C:\file3.txt", result);

Convert List Combo into Comma-Separated String in c#

My code is as below:
List<string> colorList = new List<string>();
....
sCombo = reader["Combo"].ToString();
colorList.Add(sCombo.ToString());
....
foreach (var Combo in colorList)
{
Response.Write(string.Join(",", Combo));
}
Output: D410D430D440D420 instead of D410,D430,D440,D420
What is the most simple way to convert the List<string> into a comma-separated string?
EDIT #01
Your suggestion working, but I need this new output :
'D410','D430','D440','D420'
Because use this string on sql query.
Thank you
I think this would be very handy
var colorList = new List<string>() { "D410", "D430", "D440", "D420" };
string commaSeparated = string.Join(",", colorList);
Console.WriteLine(commaSeparated);
or try solution based on Linq
Console.WriteLine(colorList.Select(s => s + ",").Aggregate((s, q) => s + q).TrimEnd(','));
The output
D410,D430,D440,D420
Edit
string result = string.Join(",", colorList.Select(e => "'" + e + "'"));
Console.WriteLine(result);
will give you
'D410','D430','D440','D420'
Without a foreach:
Response.Write(string.Join(",", colorList));
You need to output like this => 'D410','D430','D440','D420'
So try below,
string result = string.Join(",", colorList.Select(x => $"'{x}'"));
Response.Write(result);
What we did above?
Answer: First we flatten each item in your list with a single quoted ('') surrounding string and then we just pass this newly generated flatten result to join method of string with a comma (,) to get your desired output.
Output: (From Debugger)

How do I remove all non alphanumeric word from a List<string>

How do I remove all non alphanumeric words from a list of strings (List<string>) ?
I found this regex !word.match(/^[[:alpha:]]+$/) but in C# how can I obtain a new list that contains only the strings that are purely alphanumeric ?
You can use LINQ for this. Assuming you have a theList (or array or whatever) with your strings:
var theNewList = theList.Where(item => item.All(ch => char.IsLetterOrDigit(ch)));
Add a .ToList() or .ToArray() at the end if desired. This works because the String class implements IEnumerable<char>.
Regex rgx = new Regex("^[a-zA-Z0-9]*$");
List<string> list = new List<string>() { "aa", "a", "kzozd__" ,"4edz45","5546","4545asas"};
List<string> list1 = new List<string>();
foreach (var item in list)
{
if (rgx.Match(item).Success)
list1.Add(item);
}
With LINQ + regex, you can use this:
list = list.Where(s => Regex.IsMatch(s, "^[\\p{L}0-9]*$")).ToList();
^[\\p{L}0-9]*$ can recognise Unicode alphanumeric characters. If you want to use ASCII only, ^[a-zA-Z0-9]*$ will work just as well.
There's a static helper function that removes all non-alphanumeric strings from a List:
public static List<string> RemoveAllNonAlphanumeric(List<string> Input)
{
var TempList = new List<string>();
foreach (var CurrentString in Input)
{
if (Regex.IsMatch(CurrentString, "^[a-zA-Z0-9]+$"))
{
TempList.Add(CurrentString);
}
}
return TempList;
}

Comparing two strings with different orders

I have a dictionary with a list of strings that each look something like:
"beginning|middle|middle2|end"
Now what I wanted was to do this:
List<string> stringsWithPipes = new List<string>();
stringWithPipes.Add("beginning|middle|middle2|end");
...
if(stringWithPipes.Contains("beginning|middle|middle2|end")
{
return true;
}
problem is, the string i'm comparing it against is built slightly different so it ends up being more like:
if(stringWithPipes.Contains(beginning|middle2|middle||end)
{
return true;
}
and obviously this ends up being false. However, I want to consider it true, since its only the order that is different.
What can I do?
You can split your string on | and then split the string to be compared, and then use Enumerable.Except along with Enumerable.Any like
List<string> stringsWithPipes = new List<string>();
stringsWithPipes.Add("beginning|middle|middle2|end");
stringsWithPipes.Add("beginning|middle|middle3|end");
stringsWithPipes.Add("beginning|middle2|middle|end");
var array = stringsWithPipes.Select(r => r.Split('|')).ToArray();
string str = "beginning|middle2|middle|end";
var compareArray = str.Split('|');
foreach (var subArray in array)
{
if (!subArray.Except(compareArray).Any())
{
//Exists
Console.WriteLine("Item exists");
break;
}
}
This can surely be optimized, but the above is one way to do it.
Try this instead::
if(stringWithPipes.Any(P => P.split('|')
.All(K => "beginning|middle2|middle|end".split('|')
.contains(K)))
Hope this will help !!
You need to split on a delimeter:
var searchString = "beginning|middle|middle2|end";
var searchList = searchString.Split('|');
var stringsWithPipes = new List<string>();
stringsWithPipes.Add("beginning|middle|middle2|end");
...
return stringsWithPipes.Select(x => x.Split('|')).Any(x => Match(searchList,x));
Then you can implement match in multiple ways
First up must contain all the search phrases but could include others.
bool Match(string[] search, string[] match) {
return search.All(x => match.Contains(x));
}
Or must be all the search phrases cannot include others.
bool Match(string[] search, string[] match) {
return search.All(x => match.Contains(x)) && search.Length == match.Length;
}
That should work.
List<string> stringsWithPipes = new List<string>();
stringsWithPipes.Add("beginning|middle|middle2|end");
string[] stringToVerifyWith = "beginning|middle2|middle||end".Split(new[] { '|' },
StringSplitOptions.RemoveEmptyEntries);
if (stringsWithPipes.Any(s => !s.Split('|').Except(stringToVerifyWith).Any()))
{
return true;
}
The Split will remove any empty entries created by the doubles |. You then check what's left if you remove every common element with the Except method. If there's nothing left (the ! [...] .Any(), .Count() == 0 would be valid too), they both contain the same elements.

Categories

Resources