Adding Elements of generic list to dictionary - c#

I have a generic list List<String, String> ListName
I am trying to insert the values of the list, into a dictionary Dictionary<String, int>
I looked at places but only found adding elements of dictionary to list. While my requirement is opposite. I tried using toDictionary, but it didnt work for me. Not sure what went wrong.
Have anyone every attempted inserting values from list to dictionary?

I assume you mean List<string[]> because I have never seen a generic List<T,WhoAmI> before
If you are using List<string[]> you can use the ToDictionary function
List<string[]> ListName = new List<string[]>();
ListName.Add(new[] { "Stack", "1" });
ListName.Add(new[] { "Overflow", "2" });
// Select the first string([0]) as the key, and parse the 2nd([1]) as int
Dictionary<string,int> result = ListName.ToDictionary(key => key[0], value => int.Parse(value[1]));
if you are using some kind of custom object in your list you can also do it the same way
List<MyObject<string, string>> ListName = new List<MyObject<string, string>>();
Dictionary<string, int> result = ListName.ToDictionary(key => key.String1, value => int.Parse(value.String2));
public class MyObject<T, U>
{
public MyObject(T string1, U string2)
{
String1 = string1;
String2 = string2;
}
public T String1 { get; set; }
public U String2 { get; set; }
}
Note: You should add error checking around the int.Parse or use Int.TryParse if there is a chance it may not be a number.

You can use like that:
List<KeyValuePair<String, String>> ListName = new List<KeyValuePair<String, String>>();
Dictionary<String, Int32> dict = new Dictionary<String, Int32>();
ListName.ForEach(e=> dict.Add(e.key, Int32.Parse(e.Value)));

I'm not sure exactly where the integer is coming from, but something like this should work:
Dictionary<string, int> dict = new Dictionary<string, int>();
list.ForEach(x => dict.Add(x, theInteger));

Related

Create a key value pair in c#

I have been trying to create a class which has a property for key value pair, I have tried the Dictionary keyword, but I need something like this:
ClassName clsName = new ClassName();
clsName.PropertyName.Add["Key"] = value;
I want it to be dynamic property so I can send any datatype.
If we suppose that your keyvaluepair has as a key a string and as a value an int, then you could try this one:
clsName.PropertyName = new KeyValuePair<string, int>("keyName", 2);
You don't need to use the any Add method. Actually, the latter makes sence when you have a collection an you want to add to it an item. From that you have posted in your question, we can't say that this is your case.
I suggest you to simply use the "HASHTABLE" its so much easier for you.Below is syntax.
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter", 55);
1st parameter represents the key and 2nd one represents the value.So its the key value pair.
If you are after a basic class, for key and value, would
KeyValuePair<string, object>
work for you?
I'm not sure if I understood the question correctly, but apparently your requirements can be met using a generic Dictionary, where the key type parameter is string and the value type parameter is object, i.e. you could use Dictionary<string,object> like this:
public class ClassName {
public Dictionary<string, object> Dictionary { get; set; }
}
And then:
ClassName classObject = new ClassName();
classObject.Dictionary.Add("Key", new { "value" });
public class ClassName
{
public KeyValuePair<string, object> PropertyName {get; set; }
}
var c = new ClassName();
c.PropertyName = new KeyValuePair<string, object>("keyName", someValue);
or, if you need to store multiple values, use Dictionary<string, object> as type of your property.
public class ClassName
{
public ClassName()
{
this.PropertyName = new Dictionary<string, object>();
}
public Dictionary<string, object> PropertyName {get; set; }
}
var c = new ClassName();
c.PropertyName.Add("stringKey", anyValue);

LINQ GroupBy a List according to a key inside dictionary inside dictionary inside List C#

I am Creating a list that has dictionaries of dictionaries for creating Json with it from a wcf service.
im creating like this:
List<Dictionary<string, Dictionary<string, Object>>> superduperList = new List<Dictionary<string, Dictionary<string, Object>>>();
Im filling it with data and the Json Looks like this:
[
{
DepartureJ: {},
ReturnJ: {},
pricesDepartureJ: {},
pricesReturnJ: {},
DepartureSegmentsJ: {},
ArrivalSegmentsJ: {}
},
...,
...,
...,
...,
...,
]
the starting Array is the List
the first Object is the Dictionary of Dictionaries
and the Objects Within the First Dictionary are again Dictionaries with Key/Value Pairs String/object
(i use object because the type could be bool or int or string)
now a dictionary in the last level looks like this:
"DepartureJ": {
ArrivalDateTime: "2013-09-27T12:15:00",
ArrivalDateTime_str: "12:15",
StopQuantity: 0,
StopQuantity_str: "Direct",
TotalDuration: "50",
TotalDuration_str: "0h 50mins",
SeatsRemaining_str: "2",
NoBag_str: "",
NonRefundable: true,
NonRefundable_str: "Non Refundable",
FareBasisCode: "xxx-",
RoutingId: "",
GroupCompStr: "ATH-SKG-1xxxxxx-UOWA3--0",
LineCompStr: "-2013-09xxxxxxxxxxxxxxxxxxxxxA3--3,0000000-1-0--",
TotalAmount_From_Prices: 136.64
}
Now My Question is how do i Sort the Outer List From the Key TotalAmount_From_Prices which lies inside the dictionary of each dictionary of each item of the list?
i tried with groupby with LINQ but not working or don't know how :s
superduperList.GroupBy(each_result=> each_result["DepartureJ"]["TotalAmount_From_Prices"]);
its ok if i create a new list or change the existing.
Well actually i did it in a different manner.
I created a custom Class to hold the data as following:
public class each_flight
{
public Dictionary<string, object> DepartureJ = new Dictionary<string, object>();
public Dictionary<string, object> ReturnJ = new Dictionary<string, object>();
public Dictionary<string, object> pricesDepartureJ = new Dictionary<string, object>();
public Dictionary<string, object> pricesReturnJ = new Dictionary<string, object>();
public Dictionary<string, object> DepartureSegmentsJ = new Dictionary<string, object>();
public Dictionary<string, object> ArrivalSegmentsJ = new Dictionary<string, object>();
public double total_price;
}
and then i created:
List<each_flight> flights = new List<each_flight>();
and then i populated the objects in the list and then with the extra double total_price i sorted them like this:
List<each_flight> Fligths_sorted = flights.OrderBy(o => o.total_price).ToList();
so its ok now :)

How to iterate through List of Dictionaries?

I have the following code :
List<Dictionary<string, string>> allMonthsList = new List<Dictionary<string, string>>();
while (getAllMonthsReader.Read()) {
Dictionary<string, string> month = new Dictionary<string, string>();
month.Add(getAllMonthsReader["year"].ToString(),
getAllMonthsReader["month"].ToString());
allMonthsList.Add(month);
}
getAllMonthsReader.Close();
Now I'm trying to loop through all of the months, like this :
foreach (Dictionary<string, string> allMonths in allMonthsList)
How do I access the key values? Am I doing something wrong?
foreach (Dictionary<string, string> allMonths in allMonthsList)
{
foreach(KeyValuePair<string, string> kvp in allMonths)
{
string year = kvp.Key;
string month = kvp.Value;
}
}
BTW year usually has more than one month. Looks like you need a lookup here, or Dictionary<string, List<string>> for storing all months of year.
Explanation generic dictionary Dictionary<TKey, TValue> implements IEnumerable interface, which returns an enumerator that iterates through the collection. From msdn:
For purposes of enumeration, each item in the dictionary is treated as
a KeyValuePair<TKey, TValue> structure representing a value and its
key. The order in which the items are returned is undefined.
The foreach statement of the C# language requires the type of each element in the collection.
Since the Dictionary<TKey, TValue> is a collection of keys and values,
the element type is not the type of the key or the type of the value.
Instead, the element type is a KeyValuePair<TKey, TValue> of the key
type and the value type.
var months = allMonthsList.SelectMany(x => x.Keys);
You can then iterate through the IEnumerable<string> as you please which is a simple enumeration of all your keys.
Your design is wrong. Using one pair in dictionary is meaningless. You don't need to use list of dictionary.
Try this:
class YearMonth
{
public string Year { get; set; }
public string Month { get; set; }
}
List<YearMonth> allMonths = List<YearMonth>();
while (getAllMonthsReader.Read())
{
allMonths.Add(new List<YearMonth> {
Year = getAllMonthsReader["year"].ToString(),
Month = getAllMonthsReader["month"].ToString()
});
}
getAllMonthsReader.Close();
Use as:
foreach (var yearMonth in allMonths)
{
Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Year, yearMonth.Month);
}
or, if you use .Net framework 4.0 or above, you can use Tuple
List<Tuple<string, string>> allMonths = List<Tuple<string, string>>();
while (getAllMonthsReader.Read())
{
allMonths.Add(Tuple.Create( getAllMonthsReader["year"].ToString(),
getAllMonthsReader["month"].ToString())
);
}
getAllMonthsReader.Close();
Then use:
foreach (var yearMonth in allMonths)
{
Console.WriteLine("Year is {0}, Month is {1}", yearMonth.Item1, yearMonth.Item2);
}

How to create tree like structure

I want to create the data structure like below.
For this one I want go for keyvaluepair structure. But I am unable to create it.
public class NewStructure
{
public Dictionary<string, Dictionary<string, bool>> exportDict;
}
Is it a right way. If so how I can insert values to it. If I insert like
NewStructure ns = new NewStructure();
ns.exportDict.Add("mainvar",Dictionary<"subvar",true>);
it is giving compile error.
Nothing comes to my mind. Any suggestions please.
You can get rid of error by
Dictionary<string, bool> values = new Dictionary<string, bool> ();
values.Add("subvar", true);
ns.exportDict.Add("mainvar", values);
But probably you`d better try something like this:
class MyLeaf
{
public string LeafName {get; set;}
public bool LeafValue {get; set;}
}
class MyTree
{
public string TreeName {get; set;}
public List<MyLeaf> Leafs = new List<MyLeaf>();
}
And then
MyTree myTree = new MyTree();
myTree.TreeName = "mainvar";
myTree.Leafs.Add(new MyLeaf() {LeafName = "subvar", LeafValue = true});
For one, you'll have to initialize each of the dictionaries before you add to them:
exportDict = new Dictionary<string, Dictionary<string, bool>>();
Dictionary<string,bool> interiorDict = new Dictionary<string,bool>();
interiorDict.Add("subvar", true);
exportDict.Add("mainvar", interiorDict);
But if you know your interior dictionary is only going to have one key value pair then you can do:
exportDict = new Dictionary<string, KeyValuePair<string,bool>>();
exportDict.Add("mainvar", new KeyValuePair<string,bool>("subvar", true));
If you are on C# 4.0, you can accomplish this with a Dictionary<> of KeyValuePair<>
Your NewStructure would become
public class NewStructure
{
public Dictionary<string, KeyValuePair<string, bool>> exportDict =
new Dictionary<string, KeyValuePair<string, bool>>(); //this is still a dictionary!
}
and you'd use it like this:
NewStructure ns = new NewStructure();
ns.exportDict.Add("mainvar",new KeyValuePair<string,bool>("subvar",true));
With a dictionary of dictionaries you would make each "leaf" a list in itself.

Any existing Dictionary<T, List<T>> in which the value collection cannot contain the key

I need the following (using string as the type here for brevity):
MyDictionary : IDictionary<string, List<string>>
{
private readonly Dictionary<string, List<string>> _collection;
...
// The collection cannot contain the key
public void Add(string key, List<string> value)
{
_collection.Add(key, new List<string>(value.RemoveAll(p => p == key));
}
}
So in use you might have:
string myName = "Superstringcheese";
List<string> myFriends = new List<string> {"John", "Jane", "Jerry"};
string yourName = "Someone";
List<string> yourFriends = new List<string> {"John", "Bill", "Ted"};
var myDic = new MyDictionary();
// It's okay that each of us (each key) has some friends that are the same. It's not okay for me to have myself as a friend. The add method would check if the key is contained by the value collection and remove it if necessary.
myDic.Add(myName, myFriends);
myDic.Add(yourName, yourFriends);
Before I go reinventing any wheels, is there a native collection type that does this, or does anyone know of a popular implementation?
Well, I can help with this bit:
Is there a native collection type that does this?
No.

Categories

Resources