to many IF how to make quicker search c# [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Have 5 Names and 5 number.
Giv name need number.
better way?
string name = "Mark";
int x;
if(name == "John")
{
x = 1;
}else if(name == "Jimy"){
x = 2;
}else if(name == "Mark"){
x = 3;
}.... etc
return x;
result is x=3.

Often if you have a unique list of items that you want to associate with some other item, a Dictionary is a good solution. Each item in a dictionary is called a KeyValuePair, and consists of two parts: a unique key, which in this case would be the name, and a value associated with that key, which in this case is an int.
For your example, it would look something like:
// The part in parenthesis specifies that the keys will be
// case-insensitive when doing comparisons, so you can search
// for "john", "John", or "JOHN", and get the same value back
private static Dictionary<string, int> nameValues =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
{"John", 1},
{"Jimmy", 2},
{"Mark", 3}
};
And a method for retrieving the int value for a name might look like:
private static int GetIntForName(string name)
{
var valueIfNotFound = -1;
return nameValues.ContainsKey(name) ? nameValues[name] : valueIfNotFound;
}

Related

delete empty entries tuple List String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a Tuple List with 5 String values. This list contains about 250 entries with many empty entries.
How to delete these empty entries?
var program_list = new List<Tuple<string, string, string, string, string>>();
program_list.Add(Tuple.Create(program_name_String, publisher_name_String, program_version_String, install_location_String, uninstall_location_String));
I know how to delete these empty entries with a single String List. But this code won't work on Tuple List anymore.
program_names = program_names.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
program_names = program_names.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
program_names.Sort();
Thanks a lot.
I would suggest using a class rather than a tuple. Also you can still use it the same way you were using it for a string list. You just need to let it know to go deeper. Replace s with s.Item1 and you are set.
program_names = program_names.Where(s => !string.IsNullOrWhiteSpace(s.Item1)).Distinct().ToList();
but I suggest this:
public class myProgramClass
{
public string name, publisher_name, version, install_location, uninstall_location;
}
List<myProgramClass> program_list = new List<myProgramClass>();
myProgramClass new_entry = new myProgramClass() { name = "Name", publisher_name = "pub Name", version = "1.02", install_location = "dir", uninstall_location = "" };
program_list.Add(new_entry);
program_list = program_list.Where(s => string.IsNullOrWhiteSpace(s.name)).Distinct().ToList();

Which way is better to map a string array and null check? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What is the best way to map the result of adds to Codes?
result.adds contains a string array:
string[] adds = new string[] { "A", "B", "C" };
Option 1:
var car = new Car()
{
Name = request.Name,
Codes = (result.adds != null) ? adds : new string[] { }
};
In my opinion option 1 seems strange with creating a new empty string array when the result is false. I also have my doubts about mapping within the object mapping itself. On the other hand, it's direct and fast.
Option 2:
if (result.adds != null)
{
adds = results.adds;
}
var car = new Car()
{
Name = request.Name,
Codes = adds
};
Option 2 null check seems overkill to define the code seperately. It could simply be included in the mapper.
Of the two options you've presented option #1 looks the cleanest. However, you can simplify it more if you can use the null coalescing operator:
var car = new Car()
{
Name = request.Name,
Codes = result.adds ?? Array.Empty<string>()
};
This will use an empty string array in results.add is null.

Adding to Dictionary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'am trying to input som Flight information to Dictionary C# console.
But I don't know how to add those to my Dictionary.I want to store by flight number (I want flight number as a KEY). Here is my class and the hole code
public class Flight
{
public int FlightNr;
public string Destination;
}
int FlNr;
string FlDest;
List<Flight> flightList = new List<Flight>();
do
{
Console.Write("Enter flight nummer (only numbers) :");
FlNr = int.Parse(Console.ReadLine());
Console.Write("Enter destination :");
FlDest = Console.ReadLine();
flightList.Add(new Flight() { FlightNr = FlNr, Destination = FlDest });
} while (FlNr != 0);
// create Dictionary
Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>();
// My question is How to add those flights in my Dictionary ?
dictioneryFlight.Add( I don't know what to input here);
Or is something wrong with my other code? something I missed? Thank you in advance! .
If you want to use the number as key for your dictionary then you don't need a list of flights but you can use directly the dictionary
Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>();
do
{
Console.Write("Enter flight nummer (only numbers) :");
// Always check user input, do not take for granted that this is an integer
if(Int32.TryParse(Console.ReadLine(), out FlNr))
{
if(FlNr != 0)
{
// You cannot add two identical keys to the dictionary
if(dictioneryFlight.ContainsKey(FlNr))
Console.WriteLine("Fly number already inserted");
else
{
Console.Write("Enter destination :");
FlDest = Console.ReadLine();
Flight f = new Flight() { FlightNr = FlNr, Destination = FlDest };
// Add it
dictioneryFlight.Add(FlNr, f);
}
}
}
else
// This is needed to continue the loop if the user don't type a
// number because when tryparse cannot convert to an integer it
// sets the out parameter to 0.
FlNr = -1;
} while (FlNr != 0);
If you want to create a dictionary out of your list of flights, you can use ToDictionary().
var dict = flightList.ToDictionary(f => f.FlightNr);
You can do it without LINQ like so:
var dict = new Dictionary<int, Flight>();
foreach (var flight in flightList)
dict.Add(flight.FlightNr, flight);
As others have mentioned, you can skip having a List<Flight> altogether and just add directly to the dictionary when they're created instead.
One thing you might want to consider is checking if FlNr is 0 right after you parse the user input and break out of the loop right away if it is. Otherwise you'll end up with flight information for flight number 0 in your list/dictionary.
Not absolutely sure but I think you meant to store by flight number like
//declare this before your loop starts
Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>();
//Add to dictionary in your loop
dictioneryFlight.Add(FlNr, new Flight() { FlightNr = FlNr, Destination = FlDest });

Put file name into list if it contains a certain number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm starting to write a downloader.. But I want to put the files that need to extract, are required, or option in a list for later reference by the downloader.
A sample string that is fed into it would be like this:
file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2
What i want to do, is get an output like this:
Extract: file0.txt file1.txt
Required: file2.txt
Optional: file3.txt file4.txt, file5.txt
But I have no clue how to go about doing this.
The downloader will use these lists to download files the external app needs.
I'm assuming that the numbers that come after each file name are supposed to indicate what kind of file they are?
Now you definitely should try to solve this problem yourself - because thats how you learn, but here is a fairly elegant LINQ solution that creates an output identical to the example you posted.
// Define this in your class
enum FileType : byte
{
Extract = 0,
Required = 1,
Optional = 2,
}
static void Main(string[] args)
{
string input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";
// create list of files
var list = input.Split(' ').Select(file =>
{
var spl = file.Split(':');
var type = (FileType)Enum.Parse(typeof(FileType), spl[1]);
return new { Name = spl[0], Type = type };
}).ToArray();
// group by type and write to console
var group = list.GroupBy(l => l.Type);
foreach (var g in group)
{
Console.WriteLine("{0}: {1}", g.Key, String.Join(",", g.Select(a => a.Name)));
}
}
What you could do is two string split operations on the string you're fed.
var input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";
// gets each pairing
var filePairs = input.split(new[] {' '});
foreach(var filePair in filePairs)
{
var fileInfo = filePair.split(new[] {';'}); // [file0.txt, 0]
var fileName = fileInfo[0]; // file0.txt
var fileKeep = fileInfo[1]; // 0, 1, or 2.
}
From here you can do what you wish with the info you have in the foreach loop. And you can add the info to a list for storing it.

Process a string to insert key/value into a dictionary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a string of the format "Position=10,IntraDay=20,Client=30,". I want to insert it into a dictionary e.g ,, should be my key value pair of the dictionary. How to do it in an easy way .And vice versa too.
Pseudo-code, since you can surely figure the exact steps out yourself:
dict ← new Dictionary〈string, string〉
parts ← split input at ','
for each part in parts:
    key, value ← split part at '='
    add (key, value) to dict
That'd be the most trivial way. It's not necessarily efficient, it may break, depending on your data, but since we don't know anything else here, it might just as well work. You could also make the dictionary accept int values and parse the integer beforehand.
This is an example code of #Joey 's Pseudo-code:
//Your string (note: I have removed ending comma of your sample string)
string mystring = "Position=10,IntraDay=20,Client=30";
//Your dictionary
Dictionary<string, string> mydic = mystring.Split(',')
.ToDictionary(s => s.Split('=')[0],
s => s.Split('=')[1] );
private Dictionary<String, Int32> ProcessInputString(string str) {
var Dictionary = new Dictionary<String, Int32>();
var Entries = str.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach(var Entry in Entries) {
var EntryData = Entry.Split('=', StringSplitOptions.RemoveEmptyEntries);
var Key = EntryData[0];
var Value = Convert.ToInt32(EntryData[1]);
if(!Dictionary.ContainsKey(Key))
Dicationary[Key] = Value;
}
return Dictionary;
}
Go for the following:
var dic = new Dictionary<string,int>();
var Pairs = "Position=10,IntraDay=20,Client=30,".Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var pair in Pairs)
{
var p = pair.Split('=');
dic.Add(p[0],Convert.ToInt32(p[1]));
}
Hope it helps!

Categories