Creating the IEnumerable<KeyValuePair<string, string>> Objects with C#? - c#

For testing purposes, I need to create an IEnumerable<KeyValuePair<string, string>> object with the following sample key value pairs:
Key = Name | Value : John
Key = City | Value : NY
What is the easiest approach to do this?

any of:
values = new Dictionary<string,string> { {"Name", "John"}, {"City", "NY"} };
or
values = new [] {
new KeyValuePair<string,string>("Name","John"),
new KeyValuePair<string,string>("City","NY")
};
or:
values = (new[] {
new {Key = "Name", Value = "John"},
new {Key = "City", Value = "NY"}
}).ToDictionary(x => x.Key, x => x.Value);

Dictionary<string, string> implements IEnumerable<KeyValuePair<string,string>>.

var List = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>("Name", "John"),
new KeyValuePair<String, String>("City" , "NY")
};

Dictionary<string,string> testDict = new Dictionary<string,string>(2);
testDict.Add("Name","John");
testDict.Add("City","NY");
Is that what you mean, or is there more to it?

You can simply assign a Dictionary<K, V> to IEnumerable<KeyValuePair<K, V>>
IEnumerable<KeyValuePair<string, string>> kvp = new Dictionary<string, string>();
If that does not work you can try -
IDictionary<string, string> dictionary = new Dictionary<string, string>();
IEnumerable<KeyValuePair<string, string>> kvp = dictionary.Select((pair) => pair);

Related

Get dictionary key by list value

I'll take inspiration from this previous question. I have a dictionary with lists inside, and I want to get the key by a value inside one of those.
Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>
{
{"1", new List<string>{"1a", "1b"} },
{"2", new List<string>{"2a", "2b"} },
{"3", new List<string>{"3a", "3b"} },
};
I'm confident that all values inside are unique.
I want something like this:
getByValueKey(string value);
getByValueKey("2a") must be return "2".
if you want to use linq, you could write:
var result = myDict.FirstOrDefault(p => p.Value.Contains(stringTofind)).Key;
I like Frenchy's answer, but if you're looking for a non-linqy solution, then:
Dictionary<string, List<string>> myDict = new Dictionary<string, List<string>>
{
{"1", new List<string>{"1a", "1b"} },
{"2", new List<string>{"2a", "2b"} },
{"3", new List<string>{"3a", "3b"} },
};
string stringToFind = "2a";
string matchingKey = null;
foreach(KeyValuePair<string, List<string>> kvp in myDict)
{
if (kvp.Value.Contains(stringToFind))
{
matchingKey = kvp.Key;
break;
}
}
if (matchingKey != null)
{
System.Console.WriteLine("Matching Key: " + matchingKey);
}
else
{
System.Console.WriteLine("No match found.");
}

Neo4j + bolt + c#; how do you create multiple nodes via one query by passing a map as a parameter

can anyone advise how I should change my code (this is based on section 3.5.1.4.2 from the 3.0 developer manual). I am trying to create multiple nodes via one query in bolt.
using (var driver = GraphDatabase.Driver(Neo4jCredentials.Instance, AuthTokens.Basic(Neo4jCredentials.Username, Neo4jCredentials.Password)))
using (var session = driver.Session())
{
string query = "UNWIND { props } AS map CREATE(n) SET n = map";
Dictionary<string, object> myParameter = new Dictionary<string, object>();
myParameter.Add("props", "{\"props\":[{\"name\":\"Andres\",\"position\":\"Developer\"},{\"name\":\"Michael\",\"position\":\"Developer\"}]}");
return session.Run(query, myParameter);
}
The error I am getting is:
{"Expected map to be a map, but it was :`{\"props\":[{\"name\":\"Andres\",\"position\":\"Developer\"},{\"name\":\"Michael\",\"position\":\"Developer\"}]}`"}
Thanks in advance my learned friends...
Try forming your dictionary of params using an array of dictionaries:
Dictionary<string, object> myParameter = new Dictionary<string, object>();
Dictionary<string, object>[] props =
{
new Dictionary<string, object> {{"name", "Andres"}, {"position", "Developer"}},
new Dictionary<string, object> {{"name", "Michael"}, {"position", "Developer"}}
};
myParameter.Add("props",props);
or with a few less characters:
var myParameter = new Dictionary<string, object>
{
{
"props", new[]
{
new Dictionary<string, string> {{"name", "Andres"}, {"position", "Developer"}},
new Dictionary<string, string> {{"name", "Michael"}, {"position", "Developer"}}
}
}
};

How to check list orders (further properties) with NUnit?

I want NUnit tests a list order, based on two properties instead of one.
Snippet code (working):
var list = new List<Tuple<string, string>>
{
new Tuple<string, string>("aaaa", "bbbb"),
new Tuple<string, string>("bbbb", "aaaa"),
new Tuple<string, string>("aaaa", "cccc"),
new Tuple<string, string>("cccc", "bbbb")
};
var ordered = list.OrderBy(p => p.Item1).ThenBy(p => p.Item2);
Assert.That(ordered, Is.Ordered.By("Item1"));
Snippet code (what I want - not working):
var list = new List<Tuple<string, string>>
{
new Tuple<string, string>("aaaa", "bbbb"),
new Tuple<string, string>("bbbb", "aaaa"),
new Tuple<string, string>("aaaa", "cccc"),
new Tuple<string, string>("cccc", "bbbb")
};
var ordered = list.OrderBy(p => p.Item1).ThenBy(p => p.Item2);
Assert.That(ordered, Is.Ordered.By("Item1").ThenBy("Item2"));
// Below syntax works but does not return expected result
// Assert.That(ordered, Is.Ordered.By("Item1").By("Item2"));
Obviously, you know that there is no ThenBy syntax element in NUnit, but were hoping for By to apply multiple times. Neither feature is available and the CollectionOrderedConstraint only supports a single property name. It wouldn't be terribly difficult to implement either approach in NUnit, so you should consider filing an issue to request that feature.
For now, it's not possible. You should consider the workaround of creating an expected list of Tuples in the correct order and using testing the two lists for equality.
As another option you could look at the shouldly framework and do something like below
[TestMethod]
public void GivenAnUnorderListWhenCustomOrderExecutedThenItemsOrderbyItemOneThenByItemTwo()
{
var expectedOrder = new List<Tuple<string, string>>
{
new Tuple<string, string>("aaaa", "bbbb"),
new Tuple<string, string>("aaaa", "cccc"),
new Tuple<string, string>("bbbb", "aaaa"),
new Tuple<string, string>("cccc", "bbbb")
};
var list = new List<Tuple<string, string>>
{
new Tuple<string, string>("aaaa", "bbbb"),
new Tuple<string, string>("bbbb", "aaaa"),
new Tuple<string, string>("aaaa", "cccc"),
new Tuple<string, string>("cccc", "bbbb")
};
var orderedList = list.OrderBy(p => p.Item1).ThenBy(p => p.Item2);
orderedList.ShouldBe(expectedOrder);
}

How to Iterate Through GroupBy - Getting Duplicate Key Error

I can't figure out how to do this right. I want to be able to iterate this dictionary because it's for my unit test and so each pair for me is important to have in here
var invalidPageNumberAndSize = new Dictionary<string, string>
{
{"0", ""},
{"", "0"},
{"abc", ""},
{"", "abc"}
}.GroupBy(p => p.Key);
foreach (var invalidPagingCombination in invalidPageNumberAndSize)
{
Console.WriteLine(invalidPagingCombination.Key + " " + invalidPagingCombination);
}
Use a collection of KeyValuePair instead of dictionary:
var invalidPageNumberAndSize = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("0", ""),
new KeyValuePair<string, string>("", "0"),
new KeyValuePair<string, string>("abc", ""),
new KeyValuePair<string, string>("", "abc")
}.GroupBy(p => p.Key);
You are entering two keys in your dictionary that are empty:
{"", "0"},
and
{"", "abc"}
change this to
{"foo", "abc"}
and the error will go away. A dictionary can only have 1 instance of each key. You could also use a List of Tuples if you needed to:
var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("", "apple"));
list.Add(new Tuple<string, string>("", "zebra"));

Setting Key/Value Pairs

I've created a List as a property of the class, and want to set the Key/Value pairs when defining the List. I was originally using a structure but realized it's probably not the ideal solution so I changed it to a List. The problem is I'm getting an error with the syntax.
Any ideas?
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>[]
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};
Probably I'm missing something, but I would have used a Dictionary instead of
So simple....
Dictionary<string, string>formData = new Dictionary<string, string>
{
{"lsd", "first"},
{"charset", "second"}
};
and then use it in these ways:
foreach(KeyValuePair<string, string>k in formData)
{
Console.WriteLine(k.Key);
Console.WriteLine(k.Value);
}
....
if(formData.ContainsKey("lsd"))
Console.WriteLine("lsd is already in");
....
string v = formData["lsd"];
Console.WriteLine(v);
Try this:
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};
You had an extra [] in your definition. You are not creating an array, so you don't need it. Also when initializing list with some values, the values should be separated by a comma (,).
In my opinion, a better approach would be to use Tuple class:
pirvate List<Tuple<string, string>> formData = new List<Tuple<string, string>>()
{
new Tuple<string, string>("lsd",""),
new Tuple<string, string>("charset", "")
};
Change the semi-colon to a comma on the third line and remove the square brackets from the first line.
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};
Incidentally, if you change it to a Dictionary you get the ability to look up the values by their key more easily.
remove the [] from the declaration
private List<KeyValuePair<String,String>> formData = new List<KeyValuePair<String, String>>()
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};
Why [] after the constructor?
Items within collection initializer has to be separated using comma: ,.
try
private List<KeyValuePair<String, String>> formData = new List<KeyValuePair<String, String>>
{
new KeyValuePair<String, String>("lsd",""),
new KeyValuePair<String, String>("charset", "")
};

Categories