I have a Dictionary> in c#
Dictionary<string,List<string>> l_dictRawData;
which contains the values are :
KEYS VALUES
l_dictRawData["TamilNadu"] => VALUE[0] = "Chennai" VALUE[1] = "Madurai"
l_dictRawData["Andhra"] = > VALUE[0] = "Hyderabad" VALUE[1] = "Secundarabad"
l_dictRawData["Karnataka"] = > VALUE[0] = "mysore" VALUE[1] = "Bangalore"
Then i have the InputList
List<string> l_lstInput = new List<string>();
Which contains the data are :
l_lstInput[0] = "Hyderabad"
l_lstInput[1] = "Secundarabad"
The result will be the (ie) 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#
If u have any queries plz let me know
Well, a Dictionary
with what you're looking for in the value isn't really an appropriate datastructure for this, but you can do:
var query = from pair in l_dictRawData
where pair.Value.SequenceEquals(l_lstInput)
select pair.Key;
That will give all the keys matching the given value. You can then use one of query.First()
, query.FirstOrDefault()
, query.Single()
or query.SingleOrDefault()
to get a single result, depending on your requirements.
For contains option to work as like we should also consider the case of the string for eg look below
searchUserName = searchUserName.ToLower();
var results = orgUserEmailSettingsTOList.Where(c => c.UserDisplayName.ToLower().Contains("" + searchUserName + "")).ToList();
return results;
I haven't tested but you should find that this works or else is close enough to amend to your needs:
var matches = (
from kvPair in l_dictRawData
where l_lstInput.Contains(kvPair.Value)
where l_lstInput.Contains(kvPair.Key)
select new {
MatchedVal = kvPair.Value
}
).ToList();
This will return all the key values from the dictionary where the dictionary item contains both of the elements present in you l_lstInput collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.