LINQ: Get the data from the Dictionary in c# - c#

I have a Dictionary> in c#:
Dictionary<string, List<string>> l_dictRawData =
new Dictionary<string, List<string>> {
{ "TamilNadu", new List<string>{ "Chennai", "Madurai" }},
{ "Andhra", new List<string>{"Hyderabad", "Secundarabad" }},
{ "Karnataka", new List<string>{"mysore", "Bangalore" }}
};
Then I have the InputList:
List<string> l_lstInput = new List<string> { "Hyderabad", "Secundarabad" };
The result will be the (i.e) if the dictionary l_dictRawData contains both "Hyderabad" and "Secundarabad" ,then select the key value:
string l_strOutPut = "Andhra";
Here is my code :
var Query = from l_strData in l_dictRawData
from l_strItem in l_lstInput
where l_strData .Value.Contains(l_strItem )
select new { CityName = l_strItem,
StateName = l_strData.Key
};
How can i get the ouput using LINQ in c#

Do you know that the list's data will be in the same order as the dictionary value's order? If so:
var result = l_dictRawData.Where(pair => pair.Value.SequenceEqual(l_lstInput))
.Select(pair => pair.Key)
.FirstOrDefault();

Related

how to replace data list Type value with dictionary value based on matching name

I have a dictionary and list of data and
I need only data from list of data lstData, if Type is exist in dictionary.
and I need to replace Type name of lstData with name in dictionary. type1 with "X" and type3 with type3.
var dictionary = new Dictionary<string, string> { { "type1", "X" }, { "type3", "type3" } };
var lstData = new List<Data>
{
new Data {Name = "N1", Type = "type1"},
new Data {Name = "N1", Type = "type2"},
new Data {Name = "N2", Type = "type3"},
};
With below query I am able to achieve part 1), how to do part 2) ?
var x = lstData.Where(a => new List<string>(dictionary.Keys).Any(b => b == a.Type));
Expected output should be,
x = new List<Data>
{
new Data {Name = "N1", Type = "X"},
new Data {Name = "N2", Type = "type3"},
};
Using ContainsKey will be more efficient, especially for large datasets.
You can then use Select to create your new Data objects:
var x = listData
.Where(d => dictionary.ContainsKey(d.Type)) // Part 1
.Select(d => new Data { Name = d.Name, Type = dictionary[d.Type] }) // Part 2
.ToList();

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.");
}

C# Add variable value to list name

Is it possible to add a variable to a list name when using it?
Something like this:
string id = "1"; //Could be 2
List<string> List1 = new List<string> {"1","11" };
List<string> List2 = new List<string> {"2","22" };
foreach (var element in List+id)
{ //code here }
IDs could be a dozen different values, so I didn't even try with regular if(). Would that be the only way?
Use a dictionary:
var dict = new Dictionary<string, List<string>>();
dict.Add("1", new List<string> {"1","11" });
dict.Add("2", new List<string> {"2","22" });
Then you can do
foreach (var element in dict[id])
{
}

How can I populate a NameValueCollection via a parameter in a shared method?

I have a code segment:
var requestMock = new Mock<HttpRequestBase>();
var queryString = new NameValueCollection();
queryString["abc"] = "123";
queryString["qwe"] = "456";
queryString["yui"] = "678";
...
requestMock.SetupGet(rqst => rqst.QueryString).Returns(queryString);
Now, I would like to have the above segment written as a method:
var requestMock = GetRequestMock(???);
I intend to send the query string key/values which can be anything.
And the count of k/v pairs also can be anything.
public Mock<HttpRequestBase> GetRequestMock(???)
{
var requestMock = new Mock<HttpRequestBase>();
....
requestMock.SetupGet(rqst => rqst.QueryString).Returns(queryString);
return requestMock;
}
What would be the best way to do this eficiently and simply?
One way would be to use a Dictionary:
public Mock<HttpRequestBase> GetRequestMock(Dictionary<string, object> queryParms)
{
var queryString = new NameValueCollection();
foreach (KeyValuePair<string, object> kvp in queryParms)
{
queryString[kvp.Key] = Convert.ToString(kvp.Value);
}
...
}
and then you can call it like this:
GetRequestMock(new Dictionary<string, object> { { "abc", "123" }, { "qwe", "456" } } );

hashtable keys from multiple objects in linq

Hashtable mainhash = new Hashtable();
testdata td = new testdata() { value = "td" };
td.hash.Add("1", "tdvalue1");
td.hash.Add("2", "tdvalue2");
td.hash.Add("3", "tdvalue3");
td.hash.Add("4", "tdvalue4");
td.hash.Add("5", "tdvalue5");
testdata td1 = new testdata() { value = "td1" };
td1.hash.Add("1", "td1value1");
td1.hash.Add("2", "td1value2");
td1.hash.Add("3", "td1value3");
td1.hash.Add("4", "td1value4");
td1.hash.Add("5", "td1value5");
testdata td2 = new testdata() { value = "td2" };
td2.hash.Add("1", "td2value1");
td2.hash.Add("2", "td2value2");
td2.hash.Add("3", "td2value3");
td2.hash.Add("4", "td2value4");
td2.hash.Add("5", "td2value5");
testdata td3 = new testdata() { value = "td3" };
td3.hash.Add("1", "td3value1");
td3.hash.Add("2", "td3value2");
td3.hash.Add("3", "td3value3");
td3.hash.Add("4", "td3value4");
td3.hash.Add("5", "td3value5");
testdata td4 = new testdata() { value = "td4" };
td4.hash.Add("1", "td4value1");
td4.hash.Add("2", "td4value2");
td4.hash.Add("3", "td4value3");
td4.hash.Add("4", "td4value4");
td4.hash.Add("5", "td4value5");
mainhash.Add(1, td);
mainhash.Add(2, td1);
mainhash.Add(3, td2);
mainhash.Add(4, td3);
mainhash.Add(5, td4);
how to select all the keys using SelectMany by Linq into one list??
what i need to do in this??
var values = mainhash.Values.Cast<testdata>().Select(x => x.hash)
.SelectMany(x=> x.Keys);
what is wrong in this??
It doesn't know the type to use from Hashtable.Keys.
Try:
var values = mainhash.Values.Cast<testdata>().Select(x => x.hash)
.SelectMany(x => x.Keys.Cast<string>());
But better: use Dictionary<TKey,TValue> instead of Hashtable.
try below query -
var values = mainhash.Values.Cast<testdata>().SelectMany(x => x.hash.Keys.Cast<string>());
But, use dictionary instead of hashtable. It actually reduce the overhead of casting the objects.
hope above code helps you !!

Categories