delete empty entries tuple List String [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 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();

Related

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.

to many IF how to make quicker search c# [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 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;
}

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.

Copying a C# Collection to another collection [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 7 years ago.
Improve this question
I have the following list/Collection which I need to copy into another list.But the list are not having the same number of parameters. But the name of the object and types are same. Here is the class
First Class:
public class Class1
{
int locationID{get;set;}
string locationName{get;set;}
}
Second Class:
public class Class2
{
int locationID{get;set;}
string locationName{get;set;}
string identifier{get;set;}
}
In my method, I need to get the value of the List1 and Copy the same to List2(Class2). List2 is having an extra parameter identifier.
How can this be implemented in C#??
If the types Class1 and Class2 are formally unrelated, the conversion has to be implemented manually, which can be done using Linq as follows.
var NewList
= OldList.Select(
x => new Class2{ locationID = x.locationID, locationName = x.locationName }
).ToList();
var l1 = new List<Class1>();
var l2 = new List<Class2>();
l2.AddRange(l1.Select(i=>new Class2() {locationID = i.locationID,
locationName = i.locationName});
Class1 and Class2 two are two different objects and signatures and cannot just be copied from one to another. What you will need to do is iterate over one list, crate a new object, copy the property values over, and add it to the other list.
var firstList = GetFirstList() //returns List<Class1>();
var secondList = new List<Class2>();
foreach(var first in firstList)
{
var second = new Class2();
second.locationID = first.locationID;
second.locationName = first.locationName;
//you could even set the identifier property here
second.identifier = someValue;
secondList.Add(second);
}

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