I have a below code that create a dictionary from List. How can I group the dictionary base of company. As you can see Company = "Adventure" is twice in the list. So total dictionary records will be 3
class Package
{
public string Company { get; set; }
public double Weight { get; set; }
public long TrackingNumber { get; set; }
}
public static void ToDictionaryEx1()
{
List<Package> packages =
new List<Package>
{ new Package { Company = "Adventure", Weight = 25.2, TrackingNumber = 89453312L },
new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L },
new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L },
new Package { Company = "Adventure", Weight = 33.8, TrackingNumber = 4665518773L } };
// Create a Dictionary of Package objects,
// using TrackingNumber as the key.
Dictionary<long, Package> dictionary =
packages.ToDictionary(p => p.Company);
}
I am trying group by but some how not working
data.GroupBy(
x => x.Source,
(k, x) => new
{
Source = k,
Promotions = x.
.ToList()
})
.ToDictionary(x => x.Source, x => x.Promotions);
CodePudding user response:
No need to make the Linq GroupBy so complicated, simply define the key, then use ToDictionary based on the key and the grouped values.
Dictionary<string, List<Package>> dictionary = packages
.GroupBy(p => p.Company)
.ToDictionary(g => g.Key, g => g.ToList());
The key of the dictionary is a string
not a long
because you want to group by the CompanyName (which is a string).
CodePudding user response:
The ILookup
structure allows you to group items with the same key:
packages.ToLookup(p => p.Company, p => p)
I don't know whether it is suitable structure for your needs, but with this approach you don't need to call GroupBy
explicitly.
With that the result would look like this:
Dumping object(System.Linq.Lookup`2[String,Package])
[
{
[
{
Company : Adventure
TrackingNumber : 89453312
Weight : 25.2
},
{
Company : Adventure
TrackingNumber : 4665518773
Weight : 33.8
}
] },
{
[
{
Company : Lucerne Publishing
TrackingNumber : 89112755
Weight : 18.7
}
] },
{
[
{
Company : Wingtip Toys
TrackingNumber : 299456122
Weight : 6
}
] }
]