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);
}
Related
This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 3 years ago.
i create a dll with C# framework 2.0 and want use that in another applications...
but i have a problem
i cannot return two value from method
for example:
public string Two_String_Returner()
{
int aa = 50;
string bb = "Hello";
return aa.ToString();
return bb;
}
1-i must return two value, once is int and another is string
2- this return should be Apart from each other
i how can do this?
You can return an array of strings.
public string[] Two_String_Returner()
{
int aa = 50;
string bb = "Hello";
return new string[] { aa.ToString() , bb};
}
This question already has answers here:
Why does Enumerable.All return true for an empty sequence? [duplicate]
(7 answers)
Closed 7 years ago.
Consider the following code:
static void Main(string[] args)
{
List<string> items = new List<string>();
string result = null;
if(items.All(o => o == "ABC"))
{
result = "All";
}
else if(items.Any(o => o == "XYZ"))
{
result = "Any";
}
Console.WriteLine(result);
Console.Read();
}
This prints "All".
Why does an empty list satisfy an "All" condition where o == "ABC"
According to MSDN:-
Enumerable.All
Return true if every element of the source sequence passes the
test in the specified predicate, or if the sequence is empty;
otherwise, false.
So in your case since items is an empty collection it is returning true.
This is by design and also consistent with how the universal quantifier ∀ works in mathematics on sets.
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 "";
}
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.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Post your extension goodies for C# .Net (codeplex.com/extensionoverflow)
I'm fond of C# 3.0. One of my favorite parts is extension methods.
I like to think of extension methods as utility functions that can apply to a broad base of classes. I am being warned that this question is subjective and likely to be closed, but I think it's a good question, because we all have "boilerplate" code to do something relatively static like "escape string for XML" - but I have yet to find a place to collect these.
I'm especially interested in common functions that perform logging/debugging/profiling, string manipulation, and database access. Is there some library of these types of extension methods out there somewhere?
Edit: moved my code examples to an answer.
(Thanks Joel for cleaning up the code!)
You might like MiscUtil.
Also, a lot of people like this one:
public static bool IsNullOrEmpty(this string s)
{
return s == null || s.Length == 0;
}
but since 9 times out of 10 or more I'm checking that it's not null or empty, I personally use this:
public static bool HasValue(this string s)
{
return s != null && s.Length > 0;
}
Finally, one I picked up just recently:
public static bool IsDefault<T>(this T val)
{
return EqualityComparer<T>.Default.Equals(val, default(T));
}
Works to check both value types like DateTime, bool, or integer for their default values, or reference types like string for null. It even works on object, which is kind of eerie.
Here's a couple of mine:
// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
public static double UnixTicks(this DateTime dt)
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}
and a ToDelimitedString function:
// apply this extension to any generic IEnumerable object.
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> action)
{
if (source == null)
{
throw new ArgumentException("Source can not be null.");
}
if (delimiter == null)
{
throw new ArgumentException("Delimiter can not be null.");
}
string strAction = string.Empty;
string delim = string.Empty;
var sb = new StringBuilder();
foreach (var item in source)
{
strAction = action.Invoke(item);
sb.Append(delim);
sb.Append(strAction);
delim = delimiter;
}
return sb.ToString();
}
Here's Jeff's ToDelimitedString written using String.Join:
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> action) {
// guard clauses for arguments omitted for brevity
return String.Join(delimiter, source.Select(action));
}