Can i read an array in one line of code? - c#

Supposed i have an array int[] arr = {1,2,3,4}
I want to convert it into a string.
The result i want it to be like this string a = "1,2,3,4";
so can i have something "string a = arr...." to do it, instead of writing a for loop??
Thanks

As of .NET 4, you can simply do:
var result = string.Join( ",", arr );
In earlier versions,
var result = string.Join( ",", arr.Select( a => a.ToString() ).ToArray() );

You can use String.Join:
int[] arr = new [] { 4, 5, 6, 7 };
string joined = String.Join(",", arr);
See http://msdn.microsoft.com/en-us/library/57a79xd0.aspx for more info.

string result = string.Join(", ", arr.Select(item => item.ToString()).ToArray());

If you can't use .net 4 (I can't yet as our customers don't deploy it), you can use an extension method. This will work then work for all IEnumerable<T>'swith appropriately implemented .ToString() overrides. You can also pick what sort of seperator you want.
Once you have the below, you can just do string s = myenumerable.Seperated(",");
public static class EnumerableExtender
{
public static string Separated<T>(this IEnumerable<T> l, string separator)
{
var sb = new StringBuilder();
var first = true;
foreach (var o in l)
{
if (first) first = false; else sb.Append(separator);
sb.Append(o.ToString());
}
return sb.ToString();
}
}

Related

How to remove integers from a string type array?

I have an array of type string which has numbers and characters such as
string[] TagsSeperatedArray={"tag1","tag2","1234",""} i want to remove 1234 and "" from the array.
How can I do this. Can someone please help me. I am using asp.net c#.
foreach(var item in TagsSeperatedArray)
{
if()
{
}
}
One way to do this would be:
var arr = new[] { "tag1", "tag2", "1234", "" };
Console.WriteLine(string.Join(",", arr)); // tag1,tag2,1234,
var newArr = arr.Where(value => !string.IsNullOrWhiteSpace(value)
&& !int.TryParse(value, out _)).ToArray();
Console.WriteLine(string.Join(",", newArr)); // tag1,tag2
Note, however, that this allocates an extra array etc; it would be more efficient with a list, since you can directly remove:
var list = new List<string> { "tag1", "tag2", "1234", "" };
Console.WriteLine(string.Join(",", list)); // tag1,tag2,1234,
list.RemoveAll(value => string.IsNullOrWhiteSpace(value) || int.TryParse(value, out _));
Console.WriteLine(string.Join(",", list)); // tag1,tag2
You could use Linq for this, something like:
TagsSeparatedArray.Where(item => !int.TryParse(item, out int _))
This would exclude those that can be converted to int.
Based on the answer of #Marc Grawell
private string[] RemoveNumerics(string[] TheArray)
{
List<string> list = new List<string>();
list.AddRange(TheArray);
list.RemoveAll(value => string.IsNullOrWhiteSpace(value) || int.TryParse(value, out _));
return list.ToArray();
}
And in case you do not want it as a lambda expression:
foreach(string value in list)
if (string.IsNullOrWhiteSpace(value) || int.TryParse(value, out _))
list.Remove(value);
Cheers

Convert a list into a comma-separated string

My code is as below:
public void ReadListItem()
{
List<uint> lst = new List<uint>() { 1, 2, 3, 4, 5 };
string str = string.Empty;
foreach (var item in lst)
str = str + item + ",";
str = str.Remove(str.Length - 1);
Console.WriteLine(str);
}
Output: 1,2,3,4,5
What is the most simple way to convert the List<uint> into a comma-separated string?
Enjoy!
Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));
First Parameter: ","
Second Parameter: new List<uint> { 1, 2, 3, 4, 5 })
String.Join will take a list as a the second parameter and join all of the elements using the string passed as the first parameter into one single string.
You can use String.Join method to combine items:
var str = String.Join(",", lst);
Using String.Join:
string.Join<string>(",", lst);
Using LINQ aggregation:
lst .Aggregate((a, x) => a + "," + x);
If you have a collection of ints:
List<int> customerIds= new List<int>() { 1,2,3,3,4,5,6,7,8,9 };
You can use string.Join to get a string:
var result = String.Join(",", customerIds);
Enjoy!
Follow this:
List<string> name = new List<string>();
name.Add("Latif");
name.Add("Ram");
name.Add("Adam");
string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray()));
You can use String.Join for this if you are using .NET framework> 4.0.
var result= String.Join(",", yourList);
You can refer to the below example for getting a comma-separated string array from a list.
Example:
List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5
string JoinDataString = string.Join(",", testList.ToArray());
#{ var result = string.Join(",", #user.UserRoles.Select(x => x.Role.RoleName));
#result
}
I used in MVC Razor View to evaluate and print all roles separated by commas.
Try
Console.WriteLine((string.Join(",", lst.Select(x=>x.ToString()).ToArray())));
HTH
We can try like this to separate list entries by a comma:
string stations =
haul.Routes != null && haul.Routes.Count > 0 ?String.Join(",",haul.Routes.Select(y =>
y.RouteCode).ToList()) : string.Empty;
static void Main(string[] args) {
List<string> listStrings = new List<string>() {"C#", "ASP.NET", "SQL Server", "PHP", "Angular"};
string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);
Console.Write(CommaSeparateString);
Console.ReadKey();
}
private static string GenerateCommaSeparateStringFromList(List<string> listStrings){return String.Join(",", listStrings);}
Convert a list of string to a comma-separated string in C#
categories = ['sprots', 'news'];
categoriesList = ", ".join(categories)
print(categoriesList)
This is the output:
sprots, news
You can separate list entities by a comma like this:
//phones is a list of PhoneModel
var phoneNumbers = phones.Select(m => m.PhoneNumber)
.Aggregate(new StringBuilder(),
(current, next) => current.Append(next).Append(" , ")).ToString();
// Remove the trailing comma and space
if (phoneNumbers.Length > 1)
phoneNumbers = phoneNumbers.Remove(phoneNumbers.Length - 2, 2);
You can also override ToString() if your list items have more than one string:
public class ListItem
{
public string string1 { get; set; }
public string string2 { get; set; }
public string string3 { get; set; }
public override string ToString()
{
return string.Join(
","
, string1
, string2
, string3);
}
}
To get a CSV string:
ListItem item = new ListItem();
item.string1 = "string1";
item.string2 = "string2";
item.string3 = "string3";
List<ListItem> list = new List<ListItem>();
list.Add(item);
string strinCSV = (string.Join("\n", list.Select(x => x.ToString()).ToArray()));
You can make use of google-collections.jar which has a utility class called Joiner:
String commaSepString = Joiner.on(",").join(lst);
Or you can use the StringUtils class which has a function called join. To make use of StringUtils class, you need to use common-lang3.jar
String commaSepString=StringUtils.join(lst, ',');
For reference, refer this link Convert Collection into Comma Separated String

C#: Adding data to dictionary

I have a list like
List<string> TempList = new List<string> { "[66,X,X]", "[67,X,2]", "[x,x,x]" };
I need to add data to the dictionary from the above list
Dictionary<int, int> Dict = new Dictionary<int, int>();
so the Dict should contain
Key --> 66 value --> 67
i need to take 66(first value) from first string([66,X,X]) and 67(first value) from second string( [67,X,X]) and add it as a key value pair into the dictionary.
Now i'm following string replacing and looping methodology to do this .
Is there any way to do this in LINQ or Regular expression.
After your comment that you're starting from a list of lists, I understood what you were after. I'm reusing Jaroslav's 'GetNumber' function here. Wrote my sample with array of array of string, but should work just the same. The code below will throw if you have duplicate keys, which I presume is what you want if you're using a dictionary.
var input = new []
{
new [] { "[66,X,X]", "[67,X,2]", "[x,x,x]" },
new [] { "[5,X,X]", "[8,X,2]", "[x,x,x]" }
};
var query = from l in input
select new
{
Key = GetNumber(l.ElementAt(0)),
Value = GetNumber(l.ElementAt(1))
};
var dictionary = query.ToDictionary(x => x.Key, x => x.Value);
Here is an example using both string.Split() and a Regex:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> data = new List<string>() { "[66,X,X]", "[67,X,2]", "[x,x,x]" };
addToDict(data);
Console.ReadKey();
}
private static void addToDict(List<string> items)
{
string key = items[0].Split('[', ',')[1];
string val = items[1].Split('[', ',')[1];
string pattern = #"(?:^\[)(\d+)";
Match m = Regex.Match(items[0], pattern);
key = m.Groups[1].Value;
m = Regex.Match(items[1], pattern);
val = m.Groups[1].Value;
_dict.Add(key, val);
}
static Dictionary<string, string> _dict = new Dictionary<string, string>();
}
}
i suspect that your example is quite contrived though, so there may be a better solution especially if you need to process large numbers of strings into key/value pairs (i deliberately hardcoded index values because your example was quite simple and i didn't want to over complicate the answer). If the input data is consistent in format then you can make assumptions like using fixed indexes, but if there is a possibility of some variance then there may need to be more code to check the validity of it.
You can use a regular expression to extract the value from each item in the list, and if you want, use LINQ to select out two lists and zip them together (in C# 4.0):
var regex = new Regex(#"\d+");
var allValues = TempList.Select(x =>int.Parse(regex.Match(x).Value));
var dictKeys = allValues.Where((x,index)=> index % 2 == 0); //even-numbered
var dictValues = allValues.Where((x,index)=> index % 2 > 0); //odd numbered
var dict = dictKeys.Zip(dictValues, (key,value) => new{key,value})
.ToDictionary(x=>x.key,x=>x.value);
If you're using C# 3.5, you can use Eric Lippert's implementation of Zip().
IF I understand correctly: you want to create linked nodes like 66 -> 67, 67 -> 68, ... n -> n+1?
I would not use LINQ:
private static int GetNumber(string s)
{
int endPos = s.IndexOf(',');
return Int32.Parse(s.Substring(1, endPos-1));
}
And in code:
int first, second;
for (int i = 1; i < TempList.Count; i++)
{
first = GetNumber(TempList[i - 1]);
second = GetNumber(TempList[i]);
Dict.Add(first, second);
}
You should also perform checking, etc.
The sample assumes a list with at least 2 items.
List<List<string>> source = GetSource();
Dictionary<int, int> result = source.ToDictionary(
tempList => GetNumber(tempList[0]),
tempList => GetNumber(tempList[1])
);

Convert List<int> to delimited string list [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
most elegant way to return a string from List<int>
I'm not sure the easiest way to do this. I simply want to add a ; between each value and spit it out as one string. I don't see that you can do this with ToString(). I'd have to loop through and create a stringbuilder and append & add a ";".
UPDATED to use List<int> instead of List<string>
Use string.Join:
List<int> data = ..;
var result = string.Join(";", data); // (.NET 4.0+)
var result = string.Join(";", data.Select(x => x.ToString()).ToArray()); // (.NET 3.5)
string.Join(";", myList.ToArray());
Just use the join
string combinedString = String.Join(";", arrayName);
List<String> list = new List<String>() { "A", "B", "C", "D", "E" };
String joindString1 = String.Join(";", list.ToArray());
String joindString2 = list.Aggregate((s1, s2) => s1 + ";" + s2);
You can also use Enumerable.Aggregate which can give extra flexibility.
var data = new List<int> { 1,2,3 };
var sb = new StringBuilder(100);
// do some other stuff with sb
sb = data.Aggregate(sb, (b, d) => b.Append(d).Append(';'));
if( data.Count > 0 ) sb.Length--;
//do some more stuff with sb
var str = sb.ToString();

Convert a IList<int> collection to a comma separated list

Any elegant ways of converting a IList collection to a string of comma separated id's?
"1,234,2,324,324,2"
IList<int> list = new List<int>( new int[] { 1, 2, 3 } );
Console.WriteLine(string.Join(",", list));
You can do:
// Given: IList<int> collection;
string commaSeparatedInts = string.Join(",",collection.Select(i => i.ToString()).ToArray());
// list = IList<MyObject>
var strBuilder = new System.Text.StringBuilder();
foreach(var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
strBuilder = strBuilder.SubString(0, strBuilder.Length -1);
return strBuilder.ToString();
This will do it
IList<int> strings = new List<int>(new int[] { 1,2,3,4 });
string[] myStrings = strings.Select(s => s.ToString()).ToArray();
string joined = string.Join(",", myStrings);
OR entirely with Linq
string aggr = strings.Select(s=> s.ToString()).Aggregate((agg, item) => agg + "," + item);
List<int> intList = new List<int>{1,234,2,324,324,2};
var str = intList.Select(i => i.ToString()).Aggregate( (i1,i2) => string.Format("{0},{1}",i1,i2));
Console.WriteLine(str);
mstrickland has a good idea on using string builder because of its speed with larger lists. However, you can't set a stringbuilder as a string. Try this instead.
var strBuilder = new StringBuilder();
foreach (var obj in list)
{
strBuilder.Append(obj.ToString());
strBuilder.Append(",");
}
return strBuilder.ToString(0, strBuilder.Length - 1);

Categories

Resources