Convert an array to string - c#

How do I make this output to a string?
List<string> Client = new List<string>();
foreach (string listitem in lbClients.SelectedItems)
{
Client.Add(listitem);
}

You can join your array using the following:
string.Join(",", Client);
Then you can output anyway you want. You can change the comma to what ever you want, a space, a pipe, or whatever.

You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);

My suggestion:
using System.Linq;
string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());
reference:
https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

You can write like this:
string[] arr = { "Miami", "Berlin", "Hamburg"};
string s = string.Join(" ", arr);

Related

Compare list of string with string in linq

I have list of string
Like list1 contain 'pinky','smita','Rashmi','Srivani'
And string is like
String str = "pinky, Nandini'
I want to check if neither of str present in list1,proceed further.
how to do that?
If I understood correctly, you want to return false in the example case, so you can use Any method: Check if none of the elements of the list is already in the str, here is a one liner:
if (!list.Any(x=>str.Contains(x))) ....
You can use combination of .Any() with .Contains() with !,
var list1 = new List<string>(){ "pinky", "smita", "Rashmi", "Srivani" };
string str = "pinky, Nandini";
var list2 = str.Split(",");
var nameExists = list2.Any(x => list1.Contains(x));
if(!nameExists)
{
//Your code goes here.
}
As #Fildor said, you can use Intersect(). Elegant approach,
//All credit goes to #Fildor
var nameExists = list1.Intersect(list2).Any();

Good approach to sorting strings which contain number ie test 1, test10, test2

I am using C#, .NET 4.7
I have 3 strings ie.
[test.1, test.10, test.2]
I need to sort them to get:
test.1
test.2
test.10
I may get other strings like
[1test, 10test, 2test]
which should produce:
1test
2test
10test
using same approach.
Thoughts?
Thanks in advance.
You could use Parse the number using Regex and then sort the string. For example,
Regex re = new Regex(#"\d+");
var result = strArray.Where(x=>re.Match(x).Success)
.Select(x=> new { Key = int.Parse(re.Match(x).Value),Value = x})
.OrderBy(x=>x.Key).Select(x=>x.Value);
Where strArray is the collection of strings.
Please note in the above case, you are ignoring string which doesn't have a numeric part (as it wasn't described in OP). The numeric part of string is parsed using Regex, which is then used for sorting the collection.
Example,
Input
var strArray = new string[]{"1test", "10test", "2test"};
Output
1test
2test
10test
Input
var strArray = new string[]{"test.1", "test.10", "test.2"};
Outpuyt
test.1
test.2
test.10
For your first array you can do
var array = new[] { "test.1", "test.10", "test.2" };
var sortedArray = array.OrderBy(s => int.Parse(s.Substring(5, s.Length - 5)));
For the second array
var array = new[] { "1test", "2test", "10test" };
var sortedArray = array.OrderBy(s => int.Parse(s.Substring(0, s.Length - 4)));
Try this code. It uses SortedDictionary which always sort it's items by key when they are inserted.
static void Main(string[] args)
{
SortedDictionary<int, string> tuples = new SortedDictionary<int, string>();
string[] stringsToSortByNumbers = { "test.1", "test.10", "test.2" };
foreach (var item in stringsToSortByNumbers)
{
int numeric = Convert.ToInt32(new String(item.Where(Char.IsDigit).ToArray()));
tuples.Add(numeric, item);
}
foreach (var item in tuples)
{
Console.WriteLine(item.Value);
}
Console.ReadKey();
}

Convert a list of strings to a single string

List<string> MyList = (List<string>)Session["MyList"];
MyList contains values like: 12 34 55 23.
I tried using the code below, however the values disappear.
string Something = Convert.ToString(MyList);
I also need each value to be separated with a comma (",").
How can I convert List<string> Mylist to string?
string Something = string.Join(",", MyList);
Try this code:
var list = new List<string> {"12", "13", "14"};
var result = string.Join(",", list);
Console.WriteLine(result);
The result is: "12,13,14"
Entirely alternatively you can use LINQ, and do as following:
string finalString = collection.Aggregate("", (current, s) => current + (s + ","));
However, for pure readability, I suggest using either the loop version, or the string.Join mechanism.
Or, if you're concerned about performance, you could use a loop,
var myList = new List<string> { "11", "22", "33" };
var myString = "";
var sb = new System.Text.StringBuilder();
foreach (string s in myList)
{
sb.Append(s).Append(",");
}
myString = sb.Remove(sb.Length - 1, 1).ToString(); // Removes last ","
This Benchmark shows that using the above loop is ~16% faster than String.Join() (averaged over 3 runs).
You can make an extension method for this, so it will be also more readable:
public static class GenericListExtensions
{
public static string ToString<T>(this IList<T> list)
{
return string.Join(",", list);
}
}
And then you can:
string Something = MyList.ToString<string>();
I had to add an extra bit over the accepted answer. Without it, Unity threw this error:
cannot convert `System.Collections.Generic.List<string>' expression to type `string[]'
The solution was to use .ToArray()
List<int> stringNums = new List<string>();
String.Join(",", stringNums.ToArray())

How to find substring in list of strings using LINQ

i need to find out a string from collection of strings using its sub string. This sub string
must be in starting.
collection.FirstOrDefault(s => s.StartsWith(whatever))
you can do something like this,
List<string> collection = new List<string>();
collection.Add("example sample");
collection.Add("sample");
collection.Add("example");
var varSubstring = collection.Where(x => x.IndexOf("sample")==0).ToList();
foreach (var vartemp in varSubstring)
{
}

How can I trim all elements in a list?

I'm trying the following
string tl = " aaa, bbb, ccc, dddd eeeee";
var tags = new List<string>();
tags.AddRange(tl.Split(','));
tags.ForEach(x => x = x.Trim().TrimStart().TrimEnd());
var result = String.Join(",", tags.ToArray());
But it doesn't work, the tags always come back as " aaa", " bbb".
How can I trim all elements in a list?
// you can omit the final ToArray call if you're using .NET 4
var result = string.Join(",", tl.Split(',').Select(s => s.Trim()).ToArray());
If you only need the final result string, rather than the intermediate collection, then you could use a regular expression to tidy the string. You'll need to benchmark to determine whether or not the regex outperforms the split-trim-join technique:
var result = Regex.Replace(tl, #"(?<=^|,) +| +(?=,|$)", "");
Ran into the same problem. #Lee already explained that Lamda .ForEach() uses a copy.
You can write an Extension Method like this and use a for loop (foreach also not possible):
public static class StringListExtensions
{
public static void TrimAll(this List<string> stringList)
{
for (int i = 0; i < stringList.Count; i++)
{
stringList[i] = stringList[i].Trim(); //warning: do not change this to lambda expression (.ForEach() uses a copy)
}
}
}
Use it like this:
var productNumbers = new List<string>(){ "11111", " 22222 " }
productNumbers.TrimAll();
should result in: List(){ "11111", "22222" }
I didn't use the split and re-join solution (chosen solution) because there can be a comma inside one of the string items. The regex version is not self explanatory. This is old-school but safer and can be easily understood...
The reason your approach doesn't work is that the x is a copy of the current string reference being processed in the ForEach call (i.e. local to the delegate). Therefore the assignment doesn't affect the item referenced in the list.
Try
List<string> lstSelect = string_test.Split(',').Select(x => x.Trim()).ToList();
What's going on is that you're trying to modify a collection using a foreach statement- which is a no-no. Collections cannot be modified with a foreach.
You'll need to modifiy it a for loop, or, using lambdas, you can use LukeH's solution.
Your problem is that there is no comma between dddd and eeeee. If you want those to be separate, you need to split on ' ', strip the commas, and then trim extra whitespace.
string tl = " aaa, bbb, ccc, dddd eeeee";
var result = t1.Split(' ').Where(s => !String.IsNullOrEmpty())
.Select(s => s.Replace(',','').Trim())
.ToArray();
This can be easily done through LINQ one liner:
Just remember rule of Thumb :
SELECT -> For transforming the elements
WHERE -> For Filtering the elements
Now, we can use the SELECT clause to Transform all the elements:
List<string> listString = new List<string>(){"abc ", "xyz ", " Abc ", " zx"};
listString = listString.Select(x => x.Trim()).ToList();
Thats all and things are done.

Categories