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!
Related
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();
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 6 years ago.
Improve this question
C# Initialize Object With Properties of Another Instance
(A) I can do this...
var newRestaurant = new Restaurant();
newRestaurant.Cuisine = model.Cuisine;
newRestaurant.Name = model.Name;
(B) And I can write it this way...
var newRestaurant = new Restaurant() { Name = model.Name };
(C) But how come I can't write it like so...
var newRestaurant = new Restaurant() model;
(Q) Isn't (B) just an Object-Literal while (C) is an object instance?
Would love to know.
Thx
Isn't (B) just an Object-Literal while (C) is an object instance?
The short answer? No. C# doesn't use curly braces to represent object literals like JavaScript or similar languages do; C# uses curly braces to refer to blocks.
In the code
var newRestaurant = new Restaurant() { Name = model.Name };
the { Name = model.Name } part isn't an object literal, it's an initializer block. You can use a similar syntax to initialize collections like lists and dictionaries:
var myString = "string3";
var myList = new List<string>() { "string1", "string2", myString };
var myDictionary = new Dictionary<string, int>()
{
{ "string1", 1 },
{ "string2", 2 },
{ myString, 3 },
};
As you can see, the syntax of these blocks differs based on what sort of object is before them. This code is transformed by the compiler into
var myString = "string3";
var myList = new List<string>();
myList.Add("string1");
myList.Add("string2");
myList.Add(myString);
var myDictionary = new Dictionary<string, int>();
myDictionary.Add("string1", 1);
myDictionary.Add("string2", 2);
myDictionary.Add(myString, 3);
And in the case of your example, it's transformed into:
var newRestaurant = new Restaurant();
newRestaurant.Name = model.Name;
When you try and use model like var newRestaurant = new Restaurant() model;, the compiler has no idea what sorts of properties are in model or what you meant to do with them; are you trying to add to a list? Are you trying to copy all the properties? What does it do if all the properties in model don't match?
Further reading
Later versions of C# will have something called Records, which will have a similar feature to what you're describing (copying fields from one thing to another). You can read about them on the compiler's github page if you're interested, but it's pretty technical.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a Dictionary with values of array of strings. lets call it dic
Dictionary<int, string[]> dic;
how can i enumerate the items of a specific Value array?
You can iterate around the string array like this:
foreach(string s in dic[myIntKey])
{
// do something
}
Obviously you'll have issues if your dictionary does not have element at the given location so you'll need to use ContainsKey() to check if you're at all unsure.
Dictionary<int, string[]> dic = new Dictionary<int, string[]>();
string[] stringArray = dic[0];
// Enumerate through stringArray
foreach (string str in stringArray)
{
//...
}
You can do this :
Dictionary<int, string[]> dic;
//initialize your dictionary.
foreach (KeyValuePair<int, string[]> entry in dic)
{
int key = entry.Key;
foreach (string item in entry.Value)
{
//your string entries
}
}
For specific entry check :
int key = 1;
if (dic.ContainsKey(key))
{
foreach (string item in dic[key])
{
//your string entries
}
}
You can use the ForEach extension of a string[]
foreach (KeyValuePair<int, string[]> kvp in dic)
{
Array.ForEach(dic[kvp.Key], x => { System.Diagnostics.Debug.WriteLine(kvp.Key+":"+x); });
}
This question already has answers here:
regex to find a string that comes after =
(6 answers)
Closed 9 years ago.
So I asked this question before and said I wanted it in javascript but realized later on that it's unecessary data being sent. So it would be great if anybody could help me solve the same thing in C#
What I need is to get several properties out of a string.
The string will look something like:
str = "car[brand=saab][wheels=4]";
There can be more or fewer properties.
I need everything before the first [] in 1 variable.
Then I need each property and its value in a variable.
Easiest way to understand what I want is probably to check my previous question and the answer that solved it :)
I used the regex(slightly different) in your previous question.
string input = "car[brand=saab][wheels=4]";
string product = "";
Dictionary<string, string> props = new Dictionary<string, string>();
foreach (Match m in Regex.Matches(input, #"^(\w+)|\[(\w+)=(.+?)\]"))
{
if (String.IsNullOrEmpty(product))
product = m.Groups[1].Value;
else
props.Add(m.Groups[2].Value, m.Groups[3].Value);
}
try this regex:
(.+?)(\[.+?\])+
and a sample code:
var inputString = "car[brand=saab][wheels=4]";
var pattern = #"(?<v1>.+?)(?<v2>\[.+?\])+";
var v1 = Regex.Match(inputString, pattern).Groups["v1"].Value;
Dictionary<String, String> list = new Dictionary<String, String>();
foreach (Capture capture in Regex.Match(inputString, pattern).Groups["v2"].Captures)
{
var sp = capture.Value.Split('=');
list.Add(sp[0], sp[1]);
}
explain:
(?<name>subexpression)
Captures the matched subexpression into a named group.
You can do this
var lst=Regex.Matches(input,#"(\w+)((?:\[.*?\])+)")
.Cast<Match>()
.Select(x=>new
{
name=x.Groups[1].Value,
value=Regex.Matches(x.Groups[2].Value,#"(?<=\[).*?(?=\])")
.Cast<Match>()
.Select(x=>new
{
name=x.Groups[0].Value.Split('=')[0],
value=x.Groups[0].Value.Split('=')[1]
})
});
Now you can iterate over lst like this
foreach(var parent in lst)
{
parent.name;//car
foreach(var pairs in parent.value)
{
pairs.name;//brand,wheels
pairs.value;//ferrari,4
}
}
So,for input car[brand=a][wheels=4]cycle[brand=b][wheels=2]
Output would be like
car
brand,a
wheels,4
cycle
brand,b
wheels,2
Without regex:
string input = "car[brand=saab][wheels=4]";
var query = from s in input.Replace("]", "").Split('[')
let vars = s.Split('=')
let name = vars[0]
let value = vars.Length > 1 ? vars[1] : ""
select new {Name = name, Value = value};
string firstVar = query.First().Name;
Dictionary<string, string> otherVars = query
.Skip(1)
.ToDictionary(v => v.Name, v => v.Value);
You can access your variables in the dictionary like this string brand = otherVars["brand"]
Since you already have an answer using regex and your comments state it doesn't have to be with a regex, I'll offer an alternative:
The code is
string str = ("car[brand=saab][wheels=4]");
int i = str.IndexOf("[");
string[] details =str.Substring(i).Replace("]","").Split('[');
string name = str.Substring(0, i);
string brand = details[1].Split('=')[1];
string wheels = details[2].Split('=')[1];
This approach assumes the data is always going to be in the same format though; you may need some validation in there depending on your needs...