C# - Cannot implicitly convert type ListProduct to ListIProduct
Yep it's a covariance limitation in C#. You can't convert a list of one type to a list of another.
Instead of:
List<contracts.IProduct> myList = new List<dto.Product>();
You have to do this
List<contracts.IProduct> myList = new List<contracts.IProduct>();
myList.Add(new dto.Product());
Eric Lippert explains why they implemented it this way:
http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx (archived)
(And why it is different than working with arrays of items).
Cannot implicitly convert type System.Collections.Generic.ListDerivedDataClass to System.Collections.Generic.ListBaseDataClass
The data
list needs to be of type List<BaseDataClass>
rather than List<DerivedDataClass>
.
For example, this will compile:
List<BaseDataClass> data = new List<DerivedDataClass>().Select(x => (BaseDataClass)x).ToList();
You can create a list and add items like so:
List<BaseDataClass> data = new List<BaseDataClass>();
data.Add(new DerivedDataClass());
Cannot implicitly convert type ListClass to ListOtherClass error
The return type must match what you are returing
So change
public List<OrgElementViewModel> ChildrenComboDataset
To
public List<OrgChartManager> ChildrenComboDataset
And it will become:
private List<OrgChartManager> myList;
public List<OrgChartManager> ChildrenComboDataset
{
get
{
IEnumerable myEnumerable = OrgChartManager.Instance().GetChildrenSerch();
myList = myEnumerable.Cast<OrgChartManager>().ToList();
return myList; // You are returing List<OrgChartManager>
}
}
Cannot implicitly convert type Listanonymous type: .. to IEnumerableProduct
Its seems that your expected return output is combination of both Product
and ProductType
model class. So make a DTO (Data Transfer Object) class as follows which will contain all the fields of your output query.
public class ProductDto
{
public long ProductId { get; set; }
public string Number { get; set; }
public double Amount { get; set; }
public double PrimeCostEUR { get; set; }
public string ProductTypeName { get; set; }
}
Now write your controller method as follows where return type of the method is IEnumerable<ProductDto>
:
public async Task<IEnumerable<ProductDto>> TestProducts()
{
var items = await _context.Products.Select(p => new ProductDto
{
ProductId= p.ProductId,
Number= p.Number,
Amount= p.Amount,
PrimeCostEUR= p.PrimeCostEUR,
ProductTypeName = p.ProductType.NameType
}).ToListAsync();
return items;
}
Moreover you don't need explicit LINQ join as you did, you can achieve the same thing using EF projection as I have done with more simplicity.
Cannot implicitly convert type 'string' to 'System.Collections.Generic.Liststring' c# class getter
Change the return type of the getter to string
instead of List<string>
.
public string Food // <-- return type should be string, not List<string>
{
get {
string aliments = "";
foreach (string aliment in Food)
{
aliments += $"{aliment} ";
}
return aliments;
}
}
Cannot implicitly convert type 'System.Collections.Generic.List in asp mvc
Use this:
var qstudent = from s in _db.Tbl_Students
join pr in _db.Tbl_Pye_Reshte on s.StudentID equals pr.StudentID
join r in _db.Tbl_Reshte on pr.ReshteID equals r.ReshteID
join p in _db.Tbl_Paye on pr.PayeID equals p.PayeID
orderby p.PayeID descending
select new Tbl_Students { StudentName = s.StudentName, StudentFamily = s.StudentFamily, StudentImage = s.StudentImage, StudentPayeName = p.PayeName, StudentReshtName = r.ReshteName };
return qstudent.ToList();
Select new { ... }
will just create an anonymous type whch can´t be converted to anything except object
.
Just as an aside: you should consider naming your types depending on what an entity is within your application, in your example Student
, not the table where the entity is stored.
Error: “Cannot implicitly convert type”
The return type of your method is TimeWorkMonthlies
but inside the method body return List<TimeWorkMonthlies>
You should either
- change your method return type to
IEnumerable<TimeWorkMonthlies>
(You could useList<TimeWorkMonthlies>
but using an interface to abstract a collection type is better for many reasons) - Use
FirstOrDefault
,First
,SingleOrDefault
orSingle
extension methods of IEnumerable if you aim to return only one element and you do not care about anything except for the first element
Which of those methods is better depends on your data and search criteria - i.e. whether you expect this ID
to be unique or not.
From your semantics it looks like you're doing a sort of repository like ID lookup, so my guess would be solution 2) and using Single
or SingleOrDefault
The last choice is how you want your program to behave if nothing is found by ID
- If you want an exception, use
Single
- If you want a
null
useSingleOrDefault
In Summary, all you have to do is change your last line of code to
return result.Single();
(And ofcourse, you don't need a call to ToList()
just before that)
Cannot implicitly convert type [concrete] to [interface]
The accepted answer appears to be correct, but there are better ways to solve this problem. The preferred solution would be:
IEnumerable<IImportOrderLineModel> lines =
items.Where(x => x.OrderNumber == order.OrderNumber);
order.Lines = lines.ToList();
This solution eliminates two issues with the solution in Renat's answer:
- You start with a list and end with a list, so you'll need to create at least one new list. But
FindAll
creates another list, unnecessarily. That's extra work, extra collection pressure, and so on, in exchange for no benefit. - The
Cast<IImportOrderLineModel>
operation similarly creates a new enumerator, but it is unnecessary; you can always simply do a covariant reference conversion for free toIEnumerable<IImportOrderLineModel>
.
Related Topics
What Are the Limitations of SQLdependency
"Could Not Load Type [Namespace].Global" Causing Me Grief
Loading Multiple Versions of the Same Assembly
Windows.Ui.Notifications Is Missing
Dependency Injection in Unit of Work Pattern Using Repositories
Using Case/Switch and Gettype to Determine the Object
How to "Kill" Background Worker Completely
Leave Only Two Decimal Places After the Dot
How to Check If Tcpclient Connection Is Closed
Linq to Entities Only Supports Casting Edm Primitive or Enumeration Types with Ientity Interface
Best Way to Display Decimal Without Trailing Zeroes
How to Protect Resources That May Be Used in a Multi-Threaded or Async Environment
Displaying Arabic Characters in C# Console Application
Linq .Any VS .Exists - What's the Difference