Convert List to Dictionary Using Linq and Not Worrying About Duplicates

Convert list to dictionary using linq and not worrying about duplicates

Here's the obvious, non linq solution:

foreach(var person in personList)
{
if(!myDictionary.ContainsKey(person.FirstAndLastName))
myDictionary.Add(person.FirstAndLastName, person);
}

If you don't mind always getting the last one added, you can avoid the double lookup like this:

foreach(var person in personList)
{
myDictionary[person.FirstAndLastName] = person;
}

Create Dictionary with LINQ and avoid item with the same key has already been added error

You can use GroupBy to create unique keys:

Dictionary<string, MyObject> objectDict = csvEntries
.Select(csvEntry => csvEntry.ToMyObject())
.GroupBy(x => x.UniqueKey)
.ToDictionary(grp => grp.Key, grp => grp.First());

However, instead of grp.First() you could create a collection with ToList or ToArray. On that way you don't take an arbitary object in case of duplicate keys. Or add your priority-logic in an OrderBy before First: grp => grp.OrderBy(x => Field1).ThenBy(x => x.Field2).First()

Another option is to use a Lookup<TKey, TValue> which allows duplicate keys and even non-existing keys, you get an empty sequence in that case.

var uniqueKeyLookup = csvEntries
.Select(csvEntry => csvEntry.ToMyObject())
.ToLookup(x => x.UniqueKey);
IEnumerable<MyObject> objectsFor1234 = uniqueKeyLookup["1234"]; // empty if it doesn't exist

What is the best way to find the most numerous duplicates present in a dictionary using LINQ?

Try following :

            Dictionary<int, string> dict = new Dictionary<int, string>()
{
{ 1, "Value1" },
{ 2, "Value1" },
{ 3, "Value1" },
{ 4, "Value1" },
{ 5, "Value2" },
{ 6, "Value2" },
{ 7, "Value2" },
{ 8, "Value3" },
{ 9, "Value3" },
{ 10, "Value3" },
{ 11, "Value3" },
{ 12, "Value3" },
{ 13, "Value3" }
};
var results = dict
.GroupBy(x => x.Value)
.Select(x => new { value = x.Key, count = x.Count() })
.OrderByDescending(x => x.count)
.FirstOrDefault();

Using LINQ to remove duplicates in dictionary and the count of those duplicates

Based upon what you already have

var uniqueItems = deviceInstances.Children.GroupBy(pair => pair.Value.Information.UnderlyingDeviceType) 
.Select(group => new { Pair = group.First(), Count = group.Count() })
.ToDictionary(g => g.Pair.Value.Information.UnderlyingDeviceType.ToString(), g => g.Count);

Based on this demo

Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Alpha");
dictionary.Add(2, "Bravo");
dictionary.Add(3, "Charlie");
dictionary.Add(4, "Alpha");
dictionary.Add(5, "Bravo");
dictionary.Add(6, "Alpha");

var uniqueItems = dictionary
.GroupBy(kvp => kvp.Value)
.Select(g => new { g.Key, Count = g.Count() })
.ToDictionary(g => g.Key, g => g.Count);

foreach (var kvp in uniqueItems)
{
Console.WriteLine("{0}\t{1}", kvp.Key, kvp.Value);
}

How to convert a Liststring() to Dictionarystring,string() using LINQ in C#

If you want the result as a list, there is no reason to put it in a dictionary.

Split each item and group on the key, sort the groups on the key, and select the value that you want from the group. If I understand you right, you want only the first value for each key:

List<string> lines = File.ReadAllLines(@"C:\Text.txt").ToList();
lines =
lines.Select(x => x.Split('='))
.GroupBy(a => a[0])
.OrderBy(g => g.Key)
.Select(g => g.Key + "=" + g.First()[1])
.ToList();

Is there one liner LINQ construct for creating dictionary by merging two lists and removing duplicates

Here is one way:

 var merged =
listA.Select(b => new { key = b.key, val = b.value })
.Union(listB.Select(b => new { key = b.key, val = b.value }))
.ToDictionary(m => m.key, n => n.val);;

Please note that this will not handle objects that have the same key but different value.

To deal with duplicates you'd need:

 var d = listA.Select(b => new { key = b.key, val = b.value })
.Union(listB.Select(b => new { key = b.key, val = b.value }))
.GroupBy(x => x.key)
.Select(x => x.First())
.ToDictionary(m => m.key, n => n.val);

Please note this keeps only the first record with a given key and records with the same key, but different value are lost.


Test code

public static void Main(string[] args)
{
List<ClassA> listA = new List<ClassA>() {
new ClassA() { key = "A", value = "1" },
new ClassA() { key = "B", value = "2" }};
List<ClassB> listB = new List<ClassB>() {
new ClassB() { key = "B", value = "2" },
new ClassB() { key = "C", value = "3" },
new ClassB() { key = "A", value = "4" }};

var d = (...)

foreach( var kvp in d ) {
Console.WriteLine($"{kvp.Key}: {kvp.Value} ");
}
}

Result

A: 1
B: 2
C: 3

How to convert list to dictionary using key but do not include key as element

There is an overload of the ToDictionary method that allows you to specify how the value is constructed. For example, you probably want something like this (note this also removes the need for the Select):

var data = this.DocumentTypes
.ToDictionary(
dt => dt.RowId,
dt => new { dt.Id, dt.IsDocumentType })); //<< Here we are creating a new anonymous
// type to use as the value

var jsonString = JsonConvert.SerializeObject(data);


Related Topics



Leave a reply



Submit