Distinct Values in Dictionary<TKey,TValue> - c#

I'm trying to loop over distinct values over a dictionary list:
So I have a dictionary of key value pairs .
How do I get just the distinct values of string keys from the dictionary list?

var distinctList = mydict.Values.Distinct().ToList();
Alternatively, you don't need to call ToList():
foreach(var value in mydict.Values.Distinct())
{
// deal with it.
}
Edit: I misread your question and thought you wanted distinct values from the dictionary. The above code provides that.
Keys are automatically distinct. So just use
foreach(var key in mydict.Keys)
{
// deal with it
}

Keys are distinct in a dictionary. By definition.
So myDict.Keys is a distinct list of keys.

Looping over distinct keys and doing something with each value...
foreach( dictionary.Keys )
{
// your code
}
If you're using C# 3.0 and have access to LINQ:
Just fetching the set of distinct values:
// you may need to pass Distinct an IEqualityComparer<TSource>
// if default equality semantics are not appropriate...
foreach( dictionary.Values.Distinct() )
{
}

If the dictionary is defined as:
Dictionary<string,MyType> theDictionary = ...
Then you can just use
var distinctKeys = theDictionary.Keys;
This uses the Dictionary.Keys property. If you need a list, you can use:
var dictionaryKeysAsList = theDictionary.Keys.ToList();
Since it's a dictionary, the keys will already be distinct.
If you're trying to find all of the distinct values (as opposed to keys - it wasn't clear in the question) in the dictionary, you could use:
var distinctDictionaryValues = theDictionary.Values.Distinct(); // .ToList();

Related

How can I loop over all items in a dictionary which satisfy some condition? C#

I'm currently working on a project where I have to loop over a dictionary. I only want to loop over the keys in this dictionary which contain a substring of a. So for a dictionary (key, value) I only want to loop through the pairs in this dictionary for which the key contains A.
How would I do this?
How would I do this?
Dictionaries only offer O(1) (fast) access when checking for equality. There's not a way to "select" keys that contain a value without looping:
foreach(var entry in myDictionary)
{
if(entry.Key.Contains("A"))
// do something with entry.Value
}
You could use the Where method from Linq but it doesn't offer any performance improvement (it still loops internally):
foreach(var entry in myDictionary.Where(e => e.Key.Contains("A"))
{
// do something with entry.Value
}
Lots of ways. Here is one example (not tested).
var keys = dictionary.Keys.Where(k => k.Contains(a));
foreach (var matchingKey in keys)
{
var value = dictionary[matchingKey];
// Do something
}

What type is the best for loose numerically-indexed lists in C#?

What I need is something like an array but letting me to assign an element to whatever an index at any time and check if there is already a value assigned to particular index approximately like
MyArray<string> a = new MyArray<string>();
a[10] = "ten";
bool isTheFifthElementDefined = a[5] != null; // false
Perhaps Dictionary<int, string> with its ContainsKey method could do, but isn't there a more appropriate data structure if I want an ordered collection with numeric keys only?
I am also going to need to iterate through the defined elements (with foreach or linq preferably) accessing both the value and the key of current element.
As you mentioned Dictionary seems more appropriate for this.But you can do it with generic lists,for example, when you are creating your list you can specify an element count,and you can give a default temporary value for all your elements.
List<string> myList = new List<string>(Enumerable.Repeat("",5000));
myList[2300] = "bla bla bla..";
For int:
List<int> myList = new List<int>(Enumerable.Repeat(0,5000));
For custom type:
List<MyClass> myList = new List<MyClass>(Enumerable.Repeat(new MyClass(), 100));
Ofcourse It is not the best solution...
Note: Also you can use SortedList instead of Dictionary if you want an ordered collection by keys:
SortedList<TKey, TValue> : Represents a collection of key/value pairs that are sorted by key based on the associated IComparer implementation.
If you need key/value pairs you cannot use a list, you'll need a Dictionary.
The implementation is pretty snappy so don't be too afraid about performance (as long as you don't put too much values in it).
You can iterate over it with
foreach(KeyValuePair<int, string> kvp in dict)
{
}
If you need to order it you can use a list:
List<int> ordered = new List(dict.Keys);
ordered.Sort();
foreach(int key in ordered)
{
}

How to convert a dictionary values to a list?

In windows phone, I retrieved a table in database as dictionary in LINQ. My dictionary is like this
Dictionary<int, StudentTable>
I retrieved the table from LINQ as
var studentDictionary = studContext.StudentList.Select(p => new { p.RollNo, p }).AsEnumerable().ToDictionary(kvp => kvp.RollNo, kvp => kvp);
But I want to get all the values in the studentDictionary as a
List<StudentTable>
I know it is possible by adding each dictionary values to the list by using for loop.
How can I do this without a loop. ?
Is there any other better method than a loop?
Thanks
You can use studentDictionary.Values.
PS: The same works for the keys, using studentDictionary.Keys
Your dictionary contains Value which is an object of type StudentTable. You can select that from the dictionary and apply ToList method.
var list = studentDictionary.Values.ToList();
or
var list = studentDictionary.Select(r => r.Value).ToList();

Linq: Except on two different types of dictionaries

i have 2 different types of dictionaries Dictionary<int, Fooclass> oldDic and Dictionary<int, string> barList newDic . Now i need to compare values in both dictionaries. for Example key can be in
oldDic : 1,2,3
newDic : 1,2,3,4
Expected Output : 4
Now i need to compare both dictionaries on basis of their keys
any help would be appreciated.
Edit :
Output should be like second dictionary(newDic) but this will contain some value of 2nd dictionary's(oldDic). For example
1,"fooString" Where fooString is some value in Fooclass's someproperty....
For more clarity see this which doesn't worked for me
var addedList = from list1 in baseListDic
join list2 in trackerlist on list1.Key equals list2.Key
select new { key = list1.Key, value = list1.Value._lead };
here baseListDic is oldDic and trackerlist is newDic....
Let me know if i'm still not clear...
It would be easier to just create a new dictionary based on the new dictionary ignoring items that have the same key in the old dictionary.
var result = newDic
.Where(kvp => !oldDic.ContainsKey(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Note: Despite your question saying "i need to compare values in both dictionaries" (emphasis mine) your example seems to be demonstrating just comparison of keys so I've gone with that. If it is values you need to compare you might want to give an example of what you mean and if they are easily convertible or comparable...
If you are only actually comparing the keys then you can just use the .Keys property of the dictionary which returns an IEnumerable<TKey> that you can do your linq on...
eg:
var expectedOutput = newDic.Keys.Except(oldDic.Keys);
This does rely on the key being the same type but this goes without saying if you are comparing. Of course, there is nothing stopping you from converting their types first if you do wnat to do this with different types.
Also if you wanted to then get the values in one of the dictionaries you could do something like:
var newDicValues = expectedoutput.Select(x=>newDic[x]);
Or, you know, do any other linqy stuff you feel like. :)
Try this to get the difference between two different list: If they have any common property.
var differentItems = List<Type1>.Select(d => d.Name)
.Except(List<Type2>.Select(d => d.Name));
If understood correctly, try something like this
if you have a separate dictionary moething like this Dictionary<int, Fooclass> FinalDict
IEnumerable<int> list = OldDic.Keys.Except(NewDic.Keys);
foreach (var x in list)
{
var value =new MyClass();
OldDic.TryGetValue(x,out value );
FinalDict.Add(x,value);
}
So in the Dictionary called FinalDict will have the key and related Fooclass
Hope this helps

How do I select a List from something like new Dictionary(int, List<Customer>);

Dictionary<int, List<Customer>> dictionary = new Dictionary<int, List<Customer>>();
I want to query based on the key and get a List back. Not sure how to structure the LINQ query for that.
Desired Output:
A List<Customer> for a particular key in the Dictionary.
That's what the Dictionary (as you've defined the generic arguments) will do. So, dictionary[key] will return the list. Note that it will throw an exception if you haven't initialized it already with dictionary[key] = new List<Customer>();.
You don't need to use LINQ for this, but if you really want to
int key = 1;
List<Customer> customers = dictionary.Single(item => item.Key == key).Value;
The simplest way is to just retrieve the value for the key using the regular [] operator
dictionary[key];

Categories