Prepend/Append string for each element in a string array - c#

I have some code as below:
char[] separator = { ',' };
String[] idList = m_idsFromRequest.Split(separator); //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().ToList();
m_distinctIdList = distinctIdList.ToArray();
m_idsFromRequest = string.Join(" ", distinctIdList);
currently m_idsFromRequest = ["1","2".........."] is as such.
I want to make it ["0|1","0|2".........."] like append "0|" in each element . I wanted to know id I could do it without the foreach loop.

You can use Select and String.Join:
var idsPrependedWithZero = m_idsFromRequest.Split(separator)
.Distinct() // same as in your code
.Select(id => $"0|{id}");
string result = string.Join(",", idsPrependedWithZero);

char[] separator = { ',' };
string m_idsFromRequest = "1,2,3,4,5,6";
String[] idList = m_idsFromRequest.Split(separator); //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().Select(t => "0|" + t).ToList();
m_idsFromRequest = string.Join(",", distinctIdList);
Just added the .Select() after .Distinct(). Inside the .Select you can transform each of the item in the list.
Apart from that i also added "," in your string.Join. Because you want it to be join by comma.

Related

Extract common string from two strings with Comma separated

I have two strings consisting of several words (Comma separated). If string 1 consisting of words (; separated) which is to be ignored if it presents in string 2, below are the strings
var compToIgnore="Samsung,Motorola,Amazon";
var allCompanies="Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
var icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var c in listOfCompanies)
{
if (c.BrandId.StartsWith("A2"))
{
var item = allCompanies.Where(x => !icm.Contains(x));
var result = string.Join(",", item);
}
}
In result variable I wanted to have final result as "Godrej,Videocon,Huawei,Alibaba"
I don't see any proper result with above code
You can try Linq in order to query allCompanies:
using System.Linq;
...
var compToIgnore = "Samsung,Motorola,Amazon";
var allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
string result = string.Join(",", allCompanies
.Split(',')
.Except(compToIgnore.Split(',')));
Note, that Except removes all duplicates. If you want to preserve them, you can use HashSet<string> and Where instead of Except:
HashSet<string> exclude = new HashSet<string>(compToIgnore.Split(','));
string result = string.Join(",", allCompanies
.Split(',')
.Where(item => !exclude.Contains(item)));
Try following :
string compToIgnore = "Samsung,Motorola,Amazon";
string allCompanies = "Godrej,Samsung,Videocon,Huawei,Motorola,Alibaba,Amazon";
string[] icm = compToIgnore.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] ac = allCompanies.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string results = string.Join(",", ac.Where(x => !icm.Contains(x)));

Check a pattern in a string then convert it to upper case

I was not clear with my previous question
I have a list: new List<string> { "lts", "mts", "cwts", "rotc" };
Now I wan't to check a pattern in string that starts or ends with a forward slash like this: "cTws/Rotc/lTs" or "SomethingcTws cWtS/Rotc rOtc".
and convert to upper case only the string that starts/ends with a forward slash based on the list that I have.
So the output should be: "CWTS/ROTC/LTS", "SomethingcTws CWTS/ROTC rOtc"
I modified Sachin's answer:
List<string> replacementValues = new List<string>
{
"cwts",
"mts",
"rotc",
"lts"
};
string pattern = string.Format(#"\G({0})/?", string.Join("|", replacementValues.Select(x => Regex.Escape(x))));
Regex regExp = new Regex(pattern, RegexOptions.IgnoreCase);
string value = "Cwts/Rotc Somethingcwts1 Cwts/Rotc/lTs";
string result = regExp.Replace(value, s => s.Value.ToUpper());
Result: CWTS/ROTC Somethingcwts1 Cwts/Rotc/lTs
The desired output should be: CWTS/ROTC Somethingcwts1 CWTS/ROTC/LTS
So instead of using Regex, which I'm not really good with, I'm doing split by space then split by "/" then rejoin the strings
string val = "Somethingrotc1 cWts/rOtC/lTs Cwts";
List<string> replacementValues = new List<string>
{
"lts", "mts",
"cwts", "rotc"
};
string[] tokens = val.Split(new char[] { ' ' }, StringSplitOptions.None);
string result = string.Join(" ", tokens.Select(t =>
{
// Now split by "/"
string[] ts = t.Split(new char[] { '/' }, StringSplitOptions.None);
if (ts.Length > 1)
{
t = string.Join("/", ts.Select(x => replacementValues.Contains(x.ToLower()) ? x.ToUpper() : x));
}
return t;
}));
Output: Somethingrotc1 CWTS/ROTC/LTS Cwts
You want to change the specific words in the string to Upper case. Then you can use Regex to achieve it.
string value = "Somethingg1 Cwts/Rotc/Lts Cwts";
var replacementValues = new Dictionary<string, string>()
{
{"Cwts","CWTS"},
{"Rotc","ROTC"},
{"Lts","LTC"}
};
var regExpression = new Regex(String.Join("|", replacementValues.Keys.Select(x => Regex.Escape(x))));
var outputString = regExpression.Replace(value, s => replacementValues[s.Value]);

How to add extra charcter in a list of string?

I had a list of strings
var li = new List<string>()
{
"word1", "word2", "word3", "word4", "word5", "word6",
};
I want to concatinate some some character in each word output list will be will be
word1#,word2#,word3#,word4#,word5#,word6#
How about doing this:
li = li.Select(x => x + "#").ToList();
If you mean you want to output the string "word1#,word2#,word3#,word4#,word5#,word6#", then, after the above line, do this:
var output = String.Join(",", li);
Try this
var word = string.Join("#,",li)+"#";
It will join your strings separated with #,

String List parsing

I have a string that is like this:
Item1;Item2;Item3
but could also be
Item1
Is there a slick .net method to get that into a List?
string.split is your friend...
var yourString = "Item1;Item2;Item3";
var result = new List<string>(yourString.Split(';'));
LINQ has a way to bring the array to string, too:
var inputString = "item1;item2;item3";
var asList = inputString.Split( ';' ).ToList();
var input = "Item1;Item2;Item3";
var list = input.Split(new[] {";"}, StringSplitOptions.None).ToList();
Here's how I'd do that:
string[] arr = str.Split( new char[] { ';' } );
List<string> list = new List<string>( arr );

Best way get first word and rest of the words in a string in C#

In C#
var parameters =
from line in parameterTextBox.Lines
select new {name = line.Split(' ').First(), value = line.Split(' ').Skip(1)};
Is there a way to do this without having to split twice?
you can store the split in a let clause
var parameters =
from line in parameterTextBox.Lines
let split = line.Split(' ')
select new {name = split.First(), value = split.Skip(1)};
Sure.
var parameters = from line in parameterTextBox.Lines
let words = line.Split(' ')
select new { name = words.First(), words.skip(1) };
string Str= "one all of the rest";
Match m = Regex.match(Str,"(\w*) (\w.*)");
string wordone = m.Groups[1];
string wordtwo = m.Groups[2];
You might try this:
private Dictionary<string, string> getParameters(string[] lines)
{
Dictionary<string, string> results = new Dictionary<string, string>();
foreach (string line in lines)
{
string pName = line.Substring(0, line.IndexOf(' '));
string pVal = line.Substring(line.IndexOf(' ') + 1);
results.Add(pName, pVal);
}
return results;
}

Categories

Resources