Get keys as List<> from Dictionary for certain values - c#

While similar to this question which gave me the LINQ for part of my problem, I'm missing something that seems like it must be obvious to avoid the last step of looping through the dictionary.
I have a Dictionary and I want to get a List of keys for just the items for which the value is true. Right now I'm doing this:
Dictionary<long,bool> ItemChecklist;
...
var selectedValues = ItemChecklist.Where(item => item.Value).ToList();
List<long> values = new List<long>();
foreach (KeyValuePair<long,bool> kvp in selectedValues) {
values.Add(kvp.Key);
}
Is there any way I can go directly to a List<long> without doing that loop?

To do it in a single statement:
var values = ItemChecklist.Where(item => item.Value).Select(item => item.Key).ToList();

Try using Enumerable.Select:
List<long> result = ItemChecklist.Where(kvp => kvp.Value)
.Select(kvp => kvp.Key)
.ToList();

Related

Get all values for a certain property name in linq?

Is there a way to get all values for a certain key in linq?
Here is my collection
[PId, Pname, EnviornementName]
So I have a collection of this type, Looking for a more generic approach, where i could check the property name and do a select. Something like,
myCollection.SelectMany(item => item).Where(item==propertyName)
how can i do this?
To get an array of named property values try
var pName = "PId";
var values = myCollection
.Select(x => x.GetType().GetProperty(pName).GetValue(x, null))
.ToArray();
There are several ways to do it, for example:
var IDs = from o in myCollection
select new { o.PId };
or
var IDs = myCollection.Select(o => o.PId);
I suggest that you start with some linq tutorial: http://www.tutorialspoint.com/linq/
using System.Linq;
MyCollection.Select(x => x.Pid).ToArray();
Or to get unique values
MyCollection.Select(x => x.Pid).Distinct().ToArray();
Or better yet, a sorted array of unique values
MyCollection
.OrderBy(x => x.Pid)
.Select(x = x.Pid)
.Distinct()
.ToArray();

Linq Query Dictionary where value in List

I have a Dictionary<string, string> and another List<string>. What I am trying to achieve is a linq query to get all items out of the dictionary where any values from said dictionary are in the List<string>.
I found this post to be helpful, LINQ querying a Dictionary against a List . And was able to write the following linq expression, however my results never actually return anything.
What I have so far.
Data is the dictionary and PersonList is the list of strings.
var Persons = PersonList.Where(x => Data.ContainsKey(x))
.Select(z => new { key = z, value = Data[z] })
.ToList();
Are you looking for keys or values? If you're looking for values use
var Persons = Data.Where(kvp => PersonList.Contains(kvp.Value))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
If instead you really want keys then your code should work but another option would be:
var Persons = Data.Where(kvp => PersonList.Contains(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Try this one:
var Persons = Data.Where(x=>PersonList.Contains(x.Value))
.Select(x=>new { key=x.Key, value=x.Value})
.ToList();
I converted the result to a list, because I noticed that you used it in your code. If you want it to a dictionary, just take a look to the answer provided by D Stanley.
I think you don't have to convert it ToDictionary, because your source is a dictionary:
var Persons = Data.Where(kvp => personList.Contains(kvp.Key))
.Select(x => x);
I quickly tested it in LinqPad, but if this is a bad idea or I'm wrong, please leave a comment.

Converting Collection of Strings to Dictionary

This is probably a simple question, but the answer is eluding me.
I have a collection of strings that I'm trying to convert to a dictionary.
Each string in the collection is a comma-separated list of values that I obtained from a regex match. I would like the key for each entry in the dictionary to be the fourth element in the comma-separated list, and the corresponding value to be the second element in the comma-separated list.
When I attempt a direct call to ToDictionary, I end up in some kind of loop that appears to kick me of the BackgroundWorker thread I'm in:
var MoveFromItems = matches.Cast<Match>()
.SelectMany(m => m.Groups["args"].Captures
.Cast<Capture>().Select(c => c.Value));
var dictionary1 = MoveFromItems.ToDictionary(s => s.Split(',')[3],
s => s.Split(',')[1]);
When I create the dictionary manually, everything works fine:
var MoveFroms = new Dictionary<string, string>();
foreach(string sItem in MoveFromItems)
{
string sKey = sItem.Split(',')[3];
string sVal = sItem.Split(',')[1];
if(!MoveFroms.ContainsKey(sKey))
MoveFroms[sKey.ToUpper()] = sVal;
}
I appreciate any help you might be able to provide.
The problem is most likely that the keys have duplicates. You have three options.
Keep First Entry (This is what you're currently doing in the foreach loop)
Keys only have one entry, the first one that shows up - meaning you can have a Dictionary:
var first = MoveFromItems.Select(x => x.Split(','))
.GroupBy(x => x[3])
.ToDictionary(x => x.Key, x => x.First()[1]);
Keep All Entries, Grouped
Keys will have more than one entry (each key returns an Enumerable), and you use a Lookup instead of a Dictionary:
var lookup = MoveFromItems.Select(x => x.Split(','))
.ToLookup(x => x[3], x => x[1]);
Keep All Entries, Flattened
No such thing as a key, simply a flattened list of entries:
var flat = MoveFromItems.Select(x => x.Split(','))
.Select(x => new KeyValuePair<string,string>(x[3], x[1]));
You could also use a tuple here (Tuple.Create(x[3], x[1]);) instead.
Note: You will need to decide where/if you want the keys to be upper or lower case in these cases. I haven't done anything related to that yet. If you want to store the key as upper, just change x[3] to x[3].ToUpper() in everything above.
This splits each item and selects key out of the 4th split-value, and value out of the 2nd split-value, all into a dictionary.
var dictionary = MoveFromItems.Select(s => s.Split(','))
.ToDictionary(split => split[3],
split => split[1]);
There is no point in splitting the string twice, just to use different indices.
This would be just like saving the split results into a local variable, then using it to access index 3 and 1.
However, if indeed you don't know if keys might reoccur, I would go for the simple loop you've implemented, without a doubt.
Although you have a small bug in your loop:
MoveFroms = new Dictionary<string, string>();
foreach(string sItem in MoveFromItems)
{
string sKey = sItem.Split(',')[3];
string sVal = sItem.Split(',')[1];
// sKey might not exist as a key
if (!MoveFroms.ContainsKey(sKey))
//if (!MoveFroms.ContainsKey(sKey.ToUpper()))
{
// but sKey.ToUpper() might exist!
MoveFroms[sKey.ToUpper()] = sVal;
}
}
Should do ContainsKey(sKey.ToUpper()) in your condition as well, if you really want the key all upper cases.
This will Split each string in MoveFromItems with ',' and from them make 4th item (3rd Index) as Key and 2nd item(1st Index) as Value.
var dict = MoveFromItems.Select(x => x.Split(','))
.ToLookup(x => x[3], x => x[1]);

Convert List<MyObject> to Dictionary <obj.string, List<obj.ID>>

I would like to take a list of objects and convert it to a dictionary where the key is a field in the object, and the value is a list of a different field in the objects that match on the key. I can do this now with a loop but I feel this should be able to be accomplished with linq and not having to write the loop. I was thinking a combination of GroupBy and ToDictionary but have been unsuccessful so far.
Here's how I'm doing it right now:
var samplesWithSpecificResult = new Dictionary<string, List<int>>();
foreach(var sample in sampleList)
{
List<int> sampleIDs = null;
if (samplesWithSpecificResult.TryGetValue(sample.ResultString, out sampleIDs))
{
sampleIDs.Add(sample.ID);
continue;
}
sampleIDs = new List<int>();
sampleIDs.Add(sample.ID);
samplesWithSpecificResult.Add(sample.ResultString, sampleIDs);
}
The farthest I can get with .GroupBy().ToDictionay() is Dictionary<sample.ResultString, List<sample>>.
Any help would be appreciated.
Try the following
var dictionary = sampleList
.GroupBy(x => x.ResultString, x => x.ID)
.ToDictionary(x => x.Key, x => x.ToList());
The GroupBy clause will group every Sample instance in the list by its ResultString member, but it will keep only the Id part of each sample. This means every element will be an IGrouping<string, int>.
The ToDictionary portion uses the Key of the IGrouping<string, int> as the dictionary Key. IGrouping<string, int> implements IEnumerable<int> and hence we can convert that collection of samples' Id to a List<int> with a call to ToList, which becomes the Value of the dictionary for that given Key.
Yeah, super simple. The key is that when you do a GroupBy on IEnumerable<T>, each "group" is an object that implements IEnumerable<T> as well (that's why I can say g.Select below, and I'm projecting the elements of the original sequence with a common key):
var dictionary =
sampleList.GroupBy(x => x.ResultString)
.ToDictionary(
g => g.Key,
g => g.Select(x => x.ID).ToList()
);
See, the result of sampleList.GroupBy(x => x.ResultString) is an IEnumerable<IGrouping<string, Sample>> and IGrouping<T, U> implements IEnumerable<U> so that every group is a sequence of Sample with the common key!
Dictionary<string, List<int>> resultDictionary =
(
from sample in sampleList
group sample.ID by sample.ResultString
).ToDictionary(g => g.Key, g => g.ToList());
You might want to consider using a Lookup instead of the Dictionary of Lists
ILookup<string, int> idLookup = sampleList.ToLookup(
sample => sample.ResultString,
sample => sample.ID
);
used thusly
foreach(IGrouping<string, int> group in idLookup)
{
string resultString = group.Key;
List<int> ids = group.ToList();
//do something with them.
}
//and
List<int> ids = idLookup[resultString].ToList();
var samplesWithSpecificResult =
sampleList.GroupBy(s => s.ResultString)
.ToDictionary(g => g.Key, g => g.Select(s => s.ID).ToList());
What we 're doing here is group the samples based on their ResultString -- this puts them into an IGrouping<string, Sample>. Then we project the collection of IGroupings to a dictionary, using the Key of each as the dictionary key and enumerating over each grouping (IGrouping<string, Sample> is also an IEnumerable<Sample>) to select the ID of each sample to make a list for the dictionary value.

best way to receive a list of objects from list of KeyValuePair?

I have a list of KeyValuePairs and I want to filter it based on the key value so eventually I will get a list of values which is filtered (meaning - will not contain all the values that were in the original list).
I guess maybe the best way is some form of Lambda expression but I am not sure how to achieve it.
Thanks,
Alon
Try this:
var values = list.Where(x => x.Key == "whatever").Select(x => x.Value);
This will give you a filtered list of the values only.
Obviously you can change the way you filter your keys.
Use the following:
var filteredList = list.Where(x => x.Key == "Key");
What you're looking for some combination of LINQ extension methods (which depends on what you're exactly trying to do).
For example if I had a List of fruits to their colors and wanted to get a collection of which fruits are red, I would do something like:
var fruits = new List<KeyValuePair<string,string>>() {
new KeyValuePair<string,string>("Apple", "Green"),
new KeyValuePair<string,string>("Orange", "Orange"),
new KeyValuePair<string,string>("Strawberry", "Red"),
new KeyValuePair<string,string>("Cherry", "Red")
};
var redFruits = fruits.Where(kvp => kvp.Value == "Red").Select(kvp => kvp.Key);
// this would result in a IEnumberable<string> { "Strawberry", "Cherry" }

Categories