How to create one string from list of String? [duplicate] - c#

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Concat all strings inside a List<string> using LINQ
I am using C# 4.0, where I have a list non-null of string objects.
IList<String> Errors
What I want to do is to create a single string which has all list elements appended, one after another, with a new line character.
public String ErrorMessage
{
get { return Errors.SomeMethodHere(); }
}
One way I could think of is to loop on list of string. Is there any better way or in built System.String or LINQ method which I can use for this?

String.Join(Environment.NewLine, Errors.ToArray());

Try String.Join(Environment.NewLine, Errors.ToArray()) (for .NET 4 and up you don't need the ToArray)
More Info: http://msdn.microsoft.com/en-us/library/57a79xd0.aspx

public String ErrorMessage
{
get
{
//Use your appropriate separator instead of ','
return string.Join(",", Errors);
//return string.Join("", Errors); // Just concatenating all message
}
}

Errors.Aggregate((left, right) => string.Format(#"{0}\n{1}", left, right));

public static class MyExtensions
{
public static string ErrorMessage(this IList<String> strList)
{
string retMessage = null;
for (int i = 0; i < strList.Count; i++)
{
retMessage += strList[i].ToString() + Environment.NewLine;
}
return retMessage;
}
}
you can use the above code snippest to make an extended method to generate single string from list data.

Related

Checking Each Element in an Array to See if it is equal to a string

I have a number of elements in an array, I would like to check if a string is equal to any of these elements in the array. The number of elements in the array can change in number.
I have counted the number of elements in the array hoping to get somewhat of an advantage but haven't been able to come up with a solution.
int ArrayCount = FinalEncryptText.Count();
foreach (string i in FinalEncryptText)
{
}
Using the foreach implementation you have provided, you could include an if condition with String.Equals(string) - as Sean pointed out earlier.
But it's worth noting that String.Equals(string) without additional arguments is equivalent to using the == operator. So it's better if you specify the StringComparison type so that you express what kind of comparison you wish to perform.
For example, you could do something like this:
foreach (string element in myStringArray)
{
if(element.Equals("foo", StringComparison.CurrentCultureIgnoreCase))
...
}
You could even include the evaluation as a predicate in a LINQ query. For example, let's say you wanted to see which strings passed the evaluation:
var matches = myStringArray
.Where(element => element.Equals("foo", StringComparison.CurrentCultureIgnoreCase));
You can read more about comparing strings here.
I'm not sure what your method looks like, but I'm assuming.. you're given a random array of strings.. and you want to find a certain element in that array. Using a foreach loop:
public string Check(string[] FinalEncryptText)
{
foreach (string i in FinalEncryptText)
{
//let's say the word you want to match in that array is "whatever"
if (i == "whatever")
{
return "Found the match: " + i;
}
}
}
Using a regular for loop:
public string Check(string[] FinalEncryptText)
{
for (int i = 0; i < FinalEncryptText.Count; i++)
{
//let's say the word you want to match in that array is "whatever"
if (FinalEncryptText[i] == "whatever")
{
//Do Something
return "Found the match: " + FinalEncryptText[i];
}
}
}
Now if you already have a fixed array.. and you're passing in a string to check if that string exists in the array then it would go something like this:
public string Check(string stringToMatch)
{
for (int i = 0; i < FinalEncryptText.Count; i++)
{
//this will match whatever string you pass into the parameter
if (FinalEncryptText[i] == stringToMatch)
{
//Do Something
return "Found the match: " + FinalEncryptText[i];
}
}
}
You could use the String.Equals method in an if statement. More info on String.Method here: String.Equals Method.
if(firstString.Equals(secondString))
{
//whatever you need to do here
}

compiler is printing Strange value in c# [duplicate]

This question already has answers here:
printing all contents of array in C#
(13 answers)
How does the .ToString() method work?
(4 answers)
Closed 6 years ago.
I am using methods in c#. i returned something but compiler is not printing which i am expecting. It is printing (system.string[]). i dont know why Please help on this.
class Program
{
static void Main(string[] args)
{
string[] sub = subjects();
Console.WriteLine(sub);
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
for (int i = 0; i < limit; i++)
{
Console.WriteLine("Please Enter Subject Name " + i);
Subjects[i] = Console.ReadLine();
}
return Subjects;
}
}
The reason that Program is printing system.string[] is because class string[] does not override ToString method, so the default one is used and the default ToString returns type name, not the "value" inside type.
You can use for example String.Join method to build one string from array of strings and put given delimiter between each string:
Console.WriteLine(String.Join(", ", sub));
Console.WriteLine(sub)
wont show you anything of value (it prints the sub type), since you are not referencing any value of the sub array, e.g sub[0]. Try this:
foreach (string s in sub)
{
Console.WriteLine(s);
}
Console.WriteLine(String.Join(", ", sub));

C# string method for exact match on multiple params [duplicate]

This question already has answers here:
How do you implement the equivalent of SQL IN() using .net
(9 answers)
Closed 6 years ago.
Is there a standard String method that can take multiple parameters for exact comparison?
The equivalent in T-SQL would be IN('dog','cat',...)
Eg, if there was such a method called EqualToAny() then the below code should return false
string s="catfish";
if (s.EqualToAny("dog", "cat", "human", "dolphin"))
return true;
else
return false;
You can achieve this using the Linq Any() method.
string input = "catfish";
var mammals = new [] {"dog", "cat", "human", "dolphin"};
var result = mammals.Any(v => v == input);
result will be false for "catfish" and true for "cat".
You can also wrap this into an extension method for string:
public static bool EqualsAny(this string str, IEnumerable<string> validStrings) {
return validStrings.Any(v => v == str);
}
var result = input.EqualsAny(mammals);
Fiddle
you need EqualsAny ..
// string extension method
public static bool EqualsAny(this string source, params string[] prms)
{
return prms.Contains(source);
}

How to convert string to decimal[] in C#

Is there a way to achieve this?
I tried:
string str = "{34.10,0,0.00}"; //the string as I get it from Postgres DB
decimal[] won;
won = (decimal[])(str); //Cannot convert type 'string' to 'decimal[]'
What I would ideally want is to get into won:
won[0] = 34.10
won[1] = 0
won[2] = 0.00
Surely, I can go and split by commas, and put it in the array but I'm wondering if there's a better way.
You have to Split
won = str.Trim('{', '}').Split(',').Select(decimal.Parse).ToArray();
Edit: This part is just for fun
There is no way to cast string to a decimal[] array directly, but if you want you can add a decimal wrapper class and define implicit conversions:
class MyDecimal
{
private decimal[] _values;
public MyDecimal(int size)
{
_values = new decimal[size];
}
public decimal this[int index]
{
get { return _values[index]; }
set { _values[index] = value; }
}
public static implicit operator MyDecimal(string str)
{
var numbers = str.Trim('{', '}').Split(',');
MyDecimal d = new MyDecimal(numbers.Length);
d._values = numbers
.Select(x => decimal.Parse(x,CultureInfo.InvariantCulture))
.ToArray();
return d;
}
public static implicit operator string(MyDecimal md)
{
return string.Join(",", md._values);
}
}
Then you can do:
string str = "{34.10,0,0.00}"; //the string as I get it from Postgres DB
MyDecimal won = str;
I first misread your question. The real answer is: I know of no other way than splitting and converting in loops or using LINQ (for a LINQ sample see Selman22's answer). There's no way to cast a string to an array in one go.
While it is essentially what you suggest, you could try this:
// Remove leading and trailing brackets
string s = str.Trim('{', '}');
// Split numbers
string[] parts = s.Split(',');
decimal[] nums = new decimal[parts.Length];
// Convert
for (int i = 0; i < parts.Length; i++)
nums[i] = Convert.ToDecimal(parts[i]);
Just to play devil's advocate to those who say you have no option but to split:
var result = new JavaScriptSerializer()
.Deserialize<decimal[]>(str.Replace('{', '[').Replace('}', ']'))
here is another but probably not a better way in regex
string str = "{34.10,0,0.00}";
string pattern = #"([\d]+[\.]|[\d]?)[\d]+";
decimal[] result = Regex.Matches(str, pattern, RegexOptions.None)
.Cast<Match>()
.Select(x => decimal.Parse(x.Value))
.ToArray();
but remember Jamie Zawinski:
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
Another way would be using a StringReader and managing the split
There is no better way. At least until C# is backed up by an AI which will just guess what you are trying to do by casting one datatype into another by a custom logic.
Any programmer would guess what you want. Until now though the C# compiler is no wizard.

Can I get string.Contains to return false? [duplicate]

This question already has answers here:
'Contains()' workaround using Linq to Entities?
(10 answers)
Closed 9 years ago.
I have the following code:
string s = "123,12346";
bool b = s.Contains("1234");
The above returns true, but is there a way to return false. I have already done something like:
string[] s = {"123","12346"};
bool b = s.Contians("1234");
The above works, but I can't use the above in a contains expression with LINQ-To-Entities because it does not like Contains in pre EF 4.0.
I have an extension method which behaves like a SQL IN clause, but I need to explicitly type the parameters when I use it, I am not sure what to put between the brackets:
predicate = predicate(x=> WhereIn<>(x.Id, Ids));
x.Id is a string and Ids is a string as well. If I put WhereIn<string,string>, it complains that Argument type string is not assignable to parameter type ObjectQuery<string>
predicate comes from the PredicateBuilder: http://www.albahari.com/nutshell/predicatebuilder.aspx
Use
string searchString = "123,12346";
bool b = sep(searchString,",").Contains("1234");
//Returns this string before ","
public static string sep(string s,string delimiter)
{
int indx = s.IndexOf(delimiter);
if (indx >0)
{
return s.Substring(0, indx);
}
return "";
}

Categories

Resources