Reputation: 1899
I have enum/classes as follows
public enum TestType
{
Automatic,
Manual,
SemiManual,
SemiAutomatic
}
public class TestCase
{
public int Id { get; set; }
}
public class TestData
{
public TestType TestType { get; set; }
public int Id { get; set; }
}
Its used as follows
static void Main(string[] args)
{
List<TestData> data = new List<TestData>()
{
new TestData(){ TestType = TestType.Automatic, Id = 21 },
new TestData(){ TestType = TestType.SemiAutomatic, Id = 34 },
new TestData(){ TestType = TestType.SemiManual, Id = 13 },
new TestData(){ TestType = TestType.Manual, Id = 14 },
new TestData(){ TestType = TestType.Automatic, Id = 45 },
new TestData(){ TestType = TestType.Automatic, Id = 56 }
};
}
I need to convert this list into a Dictionary<TestType, List<TestCase>>
. For that I have code as follows.
Dictionary<TestType, List<TestCase>> dataAsDictionary =
data.GroupBy(x => x.TestType)
.ToDictionary(k => k.Key, v => v.Select( f=>
new TestCase() { Id = f.Id }));
Error CS0029 Cannot implicitly convert type '
System.Collections.Generic.Dictionary<ConsoleApp2.TestType, System.Collections.Generic.IEnumerable<ConsoleApp2.TestCase>>
' to 'System.Collections.Generic.Dictionary<ConsoleApp2.TestType, System.Collections.Generic.List<ConsoleApp2.TestCase>>
' ConsoleApp2
How can I resolve this error? I try various combinations of casting but that doesn't seem to help
Upvotes: 2
Views: 76
Reputation: 726539
You get this error because Select()
returns IEnumerable<T>
, while your Dictionary
wants values of type List<T>
.
Add a call of ToList()
to fix this problem:
Dictionary<TestType,List<TestCase>> dataAsDictionary = data
.GroupBy(x => x.TestType)
.ToDictionary(
k => k.Key
, v => v.Select( f=> new TestCase() { Id = f.Id }).ToList()
); // ^^^^^^^^^
Upvotes: 2
Reputation: 125620
Add a ToList
call:
Dictionary<TestType, List<TestCase>> dataAsDictionary =
data.GroupBy(x => x.TestType)
.ToDictionary(k => k.Key, v => v.Select( f=>
new TestCase() { Id = f.Id }).ToList());
It's needed because Select
returns IEnumerable<T>
and not List<T>
.
Upvotes: 2