Checking a dictionary if there are same values for a key - c#

I have a dictionary object like this:
CustomKeys<int, string>
eg;
1000, F1
1001, F2
1002, F1
1003, F4
1004, F2
I want to know if I have more than 1 of same values in this dictionary. I would also want to keep a note of which keys(unique id) has duplicates.
Is that possible?

It is possible using GroupBy and than Count() > 1 to keep track of which values that have duplicates.
var q = dic.GroupBy(x => x.Value)
.Select (x => new { Item = x, HasDuplicates = x.Count() > 1 });

You can find all key values they had the same values like this;
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1000, "F1");
d.Add(1001, "F2");
d.Add(1002, "F1");
d.Add(1003, "F4");
d.Add(1004, "F2");
var dublicate = d.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);
foreach (var i in dublicate)
{
Console.WriteLine(i.Key);
}
Here is a DEMO.
But if you want to get a boolean value since your item's has a same value, look at Magnus's answer which is great.

I'm not sure by what you mean by "keeping note of which has duplicate values". If you mean keeping note of the keys, you could do this:
var keys = new Dictionary<int, string>();
keys.Add(1000, "F1");
keys.Add(1001, "F2");
keys.Add(1002, "F1");
keys.Add(1003, "F4");
keys.Add(1004, "F2");
var duplicates = keys.GroupBy(i => i.Value).Select(i => new
{
keys = i.Select(x => x.Key),
value = i.Key,
count = i.Count()
});
foreach (var duplicate in duplicates)
{
Console.WriteLine("Value: {0} Count: {1}", duplicate.value, duplicate.count);
foreach (var key in duplicate.keys)
{
Console.WriteLine(" - {0}", key);
}
}
If you mean keeping track of the duplicate values only, see Sonor's answer.

Another solution could be:
var duplicates = dictionary.GroupBy( g => g.Value )
.Where( x => x.Count( ) > 1 )
.Select( x => new { Item = x.First( ), Count = x.Count( ) } )
.ToList( );

Related

Create a unique dictionary and add auto increasing integer values

How can I add a unique number to each of the distinct keys?
In the end I want a "collection" of the distinct keys but each key should have also a value which is e.g. the current_index_of_collection + 1
elements.SelectMany(p => p.Properties.Keys).Distinct();
sample output:
Key value
a 1
b 2
c 3
d 4
Are you looking for Select((value, index) => ...)?
https://msdn.microsoft.com/en-us/library/bb534869(v=vs.110).aspx
var dictionary = elements
.SelectMany(p => p.Properties.Keys)
.Distinct()
.Select((key, index) => new {
key = key,
value = index + 1,
})
.ToDictionary(item => item.key, item => item.value);
Or
var array = elements
.SelectMany(p => p.Properties.Keys)
.Distinct()
.Select((key, index) => new KeyValuePair<MyKeyType, int>(key, index + 1))
.ToArray();
You can use the Select overload which has an index field:
string[][] elements = new string[][] { new string[] { "a", "b", "a" } };
var elementsWithIndex = elements.SelectMany(p => p)
.Distinct()
.Select((p, i) => new { Key = p, Value = i + 1 });
Or in your code:
var elementsWithIndex = elements.SelectMany(p => p.Properties.Keys)
.Distinct()
.Select((p, i) => new { Key = p, Value = i + 1 });
You can simply use this.
List<string> keys = new List<string>();
keys.Add("a");
keys.Add("b");
keys.Add("c");
keys.Add("d");
keys.Add("e");
keys.Add("f");
keys.Add("g");
var fields = keys.Distinct().Select ((t,val)=> new { Key= t, Value= (val + 1)});

Getting count of duplicate items in a List [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get the count for the most common duplicate item in a list.
So far, I have:
List<string> brandList = new List<string>();
which contains 5 different soft drink brands, and the count is 100. I need to find out which brand has the most duplicates in the list and count how many duplicates there are.
Presuming that your pseudo code actually was:
List<Brand> brandList=new List<Brand>();
// fill list
and your Brand class either overrides Equals+getHashCode or has a property like BrandID which is the identifier. N youow want to get the count of the most popular brand, you can use LINQ:
var mostPopularBrand = brandList.GroupBy(b => g.BrandID)
.OrderByDescending(g => g.Count())
.Select(g => new { BrandID = g.Key, Count = g.Count()})
.First();
Console.WriteLine("Most poular brand: {0} Count: {1}",
mostPopularBrand.BrandID, mostPopularBrand.Count);
Update: If it's actually a List<string>(question was edited):
var mostPopularBrand = brandList.GroupBy(str => str)
.OrderByDescending(g => g.Count())
.Select(g => new { Brand = g.Key, Count = g.Count()})
.First();
Your code doesn't compile. Providing that you mean List<String> as a storage of brands:
var ListbrandList = new List<String>() {
"Cola",
"Juice",
"Cola",
"Water",
"Milk",
"Water",
"Cola",
};
var result = ListbrandList
.GroupBy(item => item)
.Select(item => new {
Name = item.Key,
Count = item.Count()
})
.OrderByDescending(item => item.Count)
.ThenBy(item => item.Name);
String report = String.Join(Environment.NewLine, result
.Select(item => String.Format("{0} appears {1} time(s)", item.Name, item.Count)));
you'll have report as
Cola appears 3 time(s)
Water appears 2 time(s)
Juice appears 1 time(s)
Milk appears 1 time(s)
var result = brandList
.Distinct()
.GroupJoin(brand,
k => k,
b => b,
(k, b) => new { BrandName = k, Count = b.Count() });
// An usage could be...
foreach (var r in result)
{
Debug.WriteLine("{0} Brand has {1}", r.BrandName, r.Count);
}
Without LinQ:
var result = new Dictionary<string, int>();
foreach (var brand in brandList)
{
if (!result.ContainsKey(brand))
{
var count = brandList.FindAll(x => x.Equals(brand)).Count;
result.Add(brand, count);
}
}
foreach (var r in result)
{
Console.WriteLine("{0} Brand has {1}", r.Key, r.Value);
}
You can try to do group using LINQ by Elements and calculate count
var groupedList = from l in ListbrandList
group l by l into grp
select new { key = grp.Key, cnt = grp.Count()};
Then you will have group by key (Element) and value (Count)
Something like this maybe:
var res = brandList.GroupyBy(x => x)
.Select(x => new {Key = x.Key, Count = x.Count});
Now you have a list containing the actual drink-number and the count for this number.
EDIT: Getting the brand with most count is now easy, e.g. by using:
var mostPopular = res.Single(x => x.Count == res.Max(y => y.Count));
EDIT2: Without LINQ the following might work, which is way longer and more complicated:
// get the count for every brand
Dictionary<string, int> res = new Dictionary<string, int>();
foreach(var x in brands)
{
if (!res.ContainsKey(x)) res[x] = 0;
res[x]++;
}
// now get the max count
int currentMax = 0;
string key = "";
foreach (var kv in res)
{
if (kv.Value > currentMax)
{
currentMax = kv.Value;
key = kv.Key;
}
}
Now the key should contain the brand with highest Count.
To count element with specific value in a list use :
int quantity = lst.Count(r => r == "Cola");
Example :
List<string> lst = new List<string>()
{
"Sprite",
"Cola",
"Sprite",
"Sprite",
"Cola",
"Sprite",
"Sprite",
"Cola",
"Pepsi",
"Sprite",
"Pepsi",
"Sprite",
};
string[] popularBrands = { "Cola", "Pepsi" };
int[] quantities = new int[popularBrands.Length];
for (int i = 0; i < popularBrands.Length; i++)
{
quantities[i] = lst.Count(r => r.ToUpper() == popularBrands[i].ToUpper());
Console.WriteLine("{0} : {1}", popularBrands[i], quantities[i]);
}
Output
Cola : 3
Pepsi : 2
P.S.
About this code r => r.ToUpper() == popularBrands[i].ToUpper() :
r is variable that holds a value from our list (that are taken one by one). We also use ToUpper() to make sure that our check is case insensitive.
So we basically loop through the collection taking values out of it one by one. Each time we put value to r variable and check if this variable satisfies condition. If so - we count it, if not - we just move to next value.

Search in dictionary of dictionaries

I have a dictionary defined as seen here:
Dictionary<int, Dictionary<string, object>> dict = new Dictionary<..>();
And a sample code for adding data:
dict.Add (X, new Dictionary<string, object> ());
dict [X].Add ("Car", CarObject);
dict [X].Add ("Seller", SellerObject);
dict [X].Add ("Key3", Z);
I want to search in the inner dictionary if it contains an object which then contains the following
CarObject.Name = (wildcard)X1(wildcard) of the key "Car" but I just can't seem to get a grasp of how to get into the inner dictionary and then into the object with LINQ in order to search for the value.
This will return all matching KeyValuePair<string, object>.
var query = dict.SelectMany(d => d.Value)
.Where(i => i.Key == "Key1"
&& (
i.Value is CarObject
? ((CarObject)i.Value).Name.Contains("X1")
: false
));
Try the following:
var results = dict[X].Where(x => (x.Value is CarObject) && ((CarObject)x.Value).Name.Contains("X1"));
If you want to get just the value and not the dictionary, and print the values, you can do this:
int X = 0, Z = 1;
dict[X].Add("Key1", CarObject);
dict[X].Add("Key2", SellerObject);
dict[X].Add("Key3", Z);
var results = dict[X].Where(x => (x.Value is CarObject) && ((CarObject)x.Value).Name.Contains("X1")).Select(x => x.Value);
foreach (var str in results)
Console.WriteLine(str);
You can try something like:
dict[X].Where(x => x.Value is CarObject && ((CarObject)x.Value).Name.Contains("X1"));
Or:
dict[X].Values.OfType<CarObject>().Any(x => x.Name.Contains("X1"))

C# Get dictionary first keys of duplicated values

I've got the following Dictionary:
Dictionary<int, int> myDict = new Dictionary<int, int>();
myDict.Add(0, 6);
myDict.Add(1, 10);
myDict.Add(2, 6);
myDict.Add(3, 14);
myDict.Add(4, 10);
myDict.Add(5, 10);
I already know how to get all the duplicates values:
var duplicatedValues = myDict.GroupBy(x => x.Value).Where(x => x.Count() > 1);
But what I want instead is the following: A list with all the keys of the duplicated values, but excluding the last duplicated ones. So in my list above the duplicates values are 10 and 6, and what I want is a list of the following keys: 0, 1, 4 (so excluding 2 and 5).
What is the best way to do this?
Any help would be appreciated. Thanks in advance.
EDIT: I did manage to do it with this piece of code by modifying something I found on the internet, but to be honest I find it a bit dumb to first create a string from the keys and then back into ints. I'm kinda new to the Aggregate-command, so any help how to modify the following code would be welcome:
var lookup = allIDs.ToLookup(x => x.Value, x => x.Key).Where(x => x.Count() > 1);
foreach (var item in lookup) {
var keys = item.Aggregate("", (s, v) => s + "," + v);
string[] split = keys.Split(',');
for (int i = 0; i < split.Length - 1; i++) {
if (!split[i].Equals("")) {
Console.WriteLine("removing card nr: " + split[i]);
CurrentField.removeCardFromField(Convert.ToInt32(split[i]));
}
}
}
This should do it:
var firstKeysOfDupeValues = myDict
.GroupBy(x => x.Value)
.SelectMany(x => x.Reverse().Skip(1))
.Select(p => p.Key);
.ToList();
After grouping by value, the last key for each value group is rejected using .Reverse().Skip(1) (this construct serves double duty: it also rejects the single keys of non-duplicated values) and the keys of the remaining key/value pairs are extracted into the result.
You could use
var allButLastDupKeys = myDict.GroupBy(kv => kv.Value)
.Where(g => g.Count() > 1)
.SelectMany(g => g.Take(g.Count() - 1).Select(kv => kv.Key));
string dupKeys = string.Join(",", allButLastDupKeys); // 0,1,4

How to modify key in a dictionary in C#

How can I change the value of a number of keys in a dictionary.
I have the following dictionary :
SortedDictionary<int,SortedDictionary<string,List<string>>>
I want to loop through this sorted dictionary and change the key to key+1 if the key value is greater than a certain amount.
As Jason said, you can't change the key of an existing dictionary entry. You'll have to remove/add using a new key like so:
// we need to cache the keys to update since we can't
// modify the collection during enumeration
var keysToUpdate = new List<int>();
foreach (var entry in dict)
{
if (entry.Key < MinKeyValue)
{
keysToUpdate.Add(entry.Key);
}
}
foreach (int keyToUpdate in keysToUpdate)
{
SortedDictionary<string, List<string>> value = dict[keyToUpdate];
int newKey = keyToUpdate + 1;
// increment the key until arriving at one that doesn't already exist
while (dict.ContainsKey(newKey))
{
newKey++;
}
dict.Remove(keyToUpdate);
dict.Add(newKey, value);
}
You need to remove the items and re-add them with their new key. Per MSDN:
Keys must be immutable as long as they are used as keys in the SortedDictionary(TKey, TValue).
You can use LINQ statment for it
var maxValue = 10
sd= sd.ToDictionary(d => d.key > maxValue ? d.key : d.Key +1, d=> d.Value);
If you don't mind recreating the dictionary, you could use a LINQ statment.
var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>();
var insertAt = 10;
var newValues = dictionary.ToDictionary(
x => x.Key < insertAt ? x.Key : x.Key + 1,
x => x.Value);
return new SortedDictionary<int, SortedDictionary<string, List<string>>>(newValues);
or
var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>();
var insertAt = 10;
var newValues = dictionary.ToDictionary(
x => x.Key < insertAt ? x.Key : x.Key + 1,
x => x.Value);
dictionary.Clear();
foreach(var item in newValues) dictionary.Add(item.Key, item.Value);

Categories