This question already has answers here:
Multiple string comparison with C#
(8 answers)
Closed 5 years ago.
Do you have an idea to avoid doing multiple String.Equals?
For instance:
if (interSubDir.Equals("de") || interSubDir.Equals("de-DE"))
Thanks!
If you are simply trying to make it more readable, or require less typing, you can write a string extension method like so:
public static class StringExt
{
public static bool EqualsAnyOf(this string value, params string[] targets)
{
return targets.Any(target => target.Equals(value));
}
}
Which you can use as follows:
if (interSubDir.EqualsAnyOf("de", "de-DE"))
Or
if (interSubDir.EqualsAnyOf("de", "de-DE", "en", "en-GB", "en-US"))
and so on.
Create collection of values:
string[] values = { "de", "de-DE" };
Use Contains method:
if (values.Contains(interSubDir))
It gives O(n) performance.
If your collection is very big, then you can use Array.BinarySearch method, that gives you O(log n) performance.
if (Array.BinarySearch(values, interSubDir) >= 0)
However, the collection must be sorted first.
Array.Sort(values);
Linq could come into help for you. listToChechAgainst could be simple variable or private/public property.
var listToChechAgainst = new[] { "de", "DE-de" };
if(listToChechAgainst.Any(x => innerSubDir.Equals(x)));
Related
This question already has answers here:
Convert a list to a string in C#
(14 answers)
Closed 9 months ago.
I am a mere beginner and I am trying to learn a bit of LINQ. I have a list of values and I want to receive a different list based on some computation. For example, the below is often quoted in various examples across the Internet:
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
here the "computation" is done by simply multiplying a member of the original list by itself.
I wanted to actually use a method that returns a string and takes x as an argument.
Here is the code I wrote:
namespace mytests{
class program {
static void Main (string[] args)
{
List<string> nums = new List<string>();
nums.Add("999");
nums.Add("888");
nums.Add("777");
IEnumerable<string> strings = nums.AsEnumerable().Select(num => GetStrings(num));
Console.WriteLine(strings.ToString());
}
private static string GetStrings (string num){
if (num == "999")
return "US";
else if (num == "888")
{
return "GB";
}
else
{
return "PL";
}
}
}
}
It compiles but when debugging, the method GetStrings is never accessed and the strings object does not have any members. I was expecting it to return "US", "GB", "PL".
Any advice on what I could be doing wrong?
Thanks.
IEnumerable<string>.ToString() method does not work as you expected. Result will be
System.Collections.Generic.List`1[System.String]
If you want to see the values which are held in the collection, you should create iteration.
foreach (var i in strings)
Console.WriteLine(i);
This line does two things for you. One of them is writing the values which are held in the collection to console. The other operation is iterating the collection. During iteration, values are needed and linq will execute the necessary operation (in your case GetStrings method).
Currently your code does not use the collection values, so the code does not evaluate the values and does not trigger GetStrings method.
This question already has answers here:
Simply check for multiple statements C#
(2 answers)
C# - Prettier way to compare one value against multiple values in a single line of code [duplicate]
(2 answers)
Closed 3 years ago.
I have got method:
private bool MyMethod(PlantType plantType)
{
return plantType.PlantMoveType == PlantMoveType.PlantReady
|| plantType.PlantMoveType == PlantMoveType.PlantRelase
}
Can I write it into other way? Maybe with LINQ?
One way is to put the enum values that you want to check against into an array, and call Contains.
return new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
If you are using C# 7 or later, you can also write the method as expression-bodied:
private bool MyMethod(PlantType plantType) =>
new[] { PlantMoveType.PlantReady, PlantMoveType.PlantRelase }
.Contains(plantType.PlantMoveType);
Well a small simplification would be to pass the type (enum?) of the property PlantMoveType instead of PlantType as the parameter.
Beyond that, you could declare the types to check for as e.g. an array. In case you'd like to reuse that array, you can also declare it outside the scope of the method:
private static PlantMoveType[] _plantStates =
new []{PlantMoveType.PlantReady, PlantMoveType.PlantRelase};
private bool MyMethod(PlantMoveType plantMoveType)
{
return _plantStates.Contains(plantMoveType);
}
This question already has answers here:
creating a generic sort method
(2 answers)
Closed 4 years ago.
As the title says, I had to write some code to sort either array/list of strings or integers. My OOP knowledge is really rusty since I haven't used C#/Java for a long while.
Is there a way to make it so I just need to code one function so that I don't have to overload the function
(e.g InsertSort(int [] arr) and InsertSort(string [] arr))
I heard something about using IComparable or Comparator and I took a look at the documentation of both but they seems to me that those are like more for Objects.
Thanks for any help!
Generic methods should be your friend here. Generics allow you to defer the specification of types used in method until actually used in program. You can read more on Generic here.
public T[] InsertSort<T>(T[] source)
{
// Do something
}
This can be invoked using strings/int arrays as following.
var intArray = new int[]{1,2,3};
var stringArray = new string[]{"1","2","3"};
InsertSort(intArray);
InsertSort(stringArray);
To get started, you might try something like this method.
public static IEnumerable<T> InsertSort<T>(IEnumerable<T> tmp)
{
//... Perform sorting
//... Return the sorted results as IEnumerable
}
You'll be able to send in a list or an array of the types you choose.
Usage:
List<int> listA = new List<int>();
var sortedListA = InsertSort(listA);
string[] arrA = new string[5];
var sortedArrayA = InsertSort(arrA);
This question already has answers here:
How to use Array.sort to sort an array of structs, by a specific element
(3 answers)
How would I sort through an array of structs?
(3 answers)
Closed 6 years ago.
Hello I would Like to receive some help. I have this structure:
struct data
{
public String names;
public int number;
}
I've been asked to show this structure in the console sorted alphabetically (by evaluating the names) I don't really know how to do this, I know how to sort arrays but i don't know how to sort a structure like this.
I am a beginner, any help is received thanks.
this might do the trick for you
data[] datas = new[] {
new data() { names = "Mohit", number = 3 },
//More data like that
}
and then
Array.Sort<data>(datas, (x,y) => x.names.CompareTo(y.names));
//or
Array.Sort(datas, (x,y) => string.Compare(x.names, y.names));
Or by using System.Linq
datas.OrderBy(x=>x.names);
This question already has answers here:
Case-Insensitive List Search
(8 answers)
Closed 6 years ago.
Is there a way to get the index of a item within a List with case insensitive search?
List<string> sl = new List<string>() { "a","b","c"};
int result = sl.IndexOf("B"); // should be 1 instead of -1
Try this : So there is no direct way to use IndexOf with String Comparison option for LIST, to achieve desire result you need to use Lambda expression.
int result = sl.FindIndex(x => x.Equals("B",StringComparison.OrdinalIgnoreCase));
The IndexOf method for Strings in C# has a ComparisonType argument, which should work something like this:
sl.IndexOf("yourValue", StringComparison.CurrentCultureIgnoreCase)
or
sl.IndexOf("yourValue", StringComparison.OrdinalIgnoreCase)
Documentation for this can be found here and here