Suppose we have the below entities
class PersonName
{
public int Id { get; set; }
public string Name { get; set; }
}
class PersonAddress
{
public int Id { get; set; }
public string Address { get; set; }
}
class PersonInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Now we want to combine the result of the PersonName and PersonAddress collection and the combined result want to store in List PersonInfo.
Intially the program was
List<PersonName> lstPersonName = new List<PersonName>();
Enumerable.Range(1, 10).ToList().ForEach(i => lstPersonName.Add(new PersonName { Id = i, Name = "Name" + i.ToString() }));
List<PersonAddress> lstPersonAddress = new List<PersonAddress>();
Enumerable.Range(1, 10).ToList().ForEach(i => lstPersonAddress.Add(new PersonAddress { Id = i, Address = "Address" + i.ToString() }));
List<PersonInfo> lstPersonInfo =
(
from a in lstPersonName
join b in lstPersonAddress on a.Id equals b.Id
select new
{
Prop1 = a.Id
,
Prop2 = a.Name
,
Prop3 = b.Address
}
).ToList();
Upon compiling, we encounter the below error
'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments Then we changed the .ToList() to .ToList<PersonInfo>() as under
List<PersonInfo> lstPersonInfo =
(
from a in lstPersonName
join b in lstPersonAddress on a.Id equals b.Id
select new
{
Prop1 = a.Id
,
Prop2 = a.Name
,
Prop3 = b.Address
}
).ToListList<PersonInfo>();
but with the same error.
Now why it is happening? Because, we tried to create a sequence of a new anonymous type and tried to call ToList<PersonInfo> on it which will never work. We should create a PersonInfo
directly by writing new PersonInfo { ... } as under
List<PersonInfo> lstPersonInfo =
(
from a in lstPersonName
join b in lstPersonAddress on a.Id equals b.Id
select new PersonInfo
{
Id = a.Id
,
Name = a.Name
,
Address = b.Address
}
).ToList();
Hope this is useful.