I'm trying to convert my class AllStock to ObservableCollection<AllStock> stockList but I get the following error:
The best overloaded method match for 'System.Collections.ObjectModel.Collection.Add(Haze.AllStock)' has some invalid arguments
Here is my coding:
I create my Observable Collection -
private ObservableCollection<AllStock> _stockList;
public ObservableCollection<AllStock> stockList
{
get
{
if (_stockList == null)
_stockList = new ObservableCollection<AllStock>();
return _stockList;
}
}
Inside my method -
var allStock = await service.GetSysproStockAsync();
var stock = allStock.Select(x =>
new AllStock
{
Id = x.Id,
...
MaterialThickness = x.MaterialThickness
});
stockList.Add(stock); //Error here - I want to add my 'var stock' to my ObservableCollection
dgSysproStock.ItemsSource = stockList;
Why would it be throwing out this error?
Your Linq's Select method returns an IEnumerable but your stockList.Add has no overload for this datatype (only AllStock).
foreach(AllStock aStock in stock)
stockList.Add(aStock)
should work. The ObservableCollection unfortunatley doesn't have a AddRange method like the List<>
The Add() for ObservableCollection requires a List so you need to provide a List instead.
Related
I have a table of doctors in my database. So I'm trying to get the list of the firstName of the doctors in my database.
In the ViewModel class I'm using this code to get it
public List DoctorsList ()
{
// string mainconn = Configuration
List ListOfDoctors;
using (var context = new GlabDbContext())
{
var result = (from c in context.Doctors
select c.LastName).ToList();
ListOfDoctors = result;
}
return ListOfDoctors;
}
I want to use this function like a method of my ViewModel class an it will have a return.
But I'm getting an error saying that:
Impossible to convert implicitely 'System.Collections.Generic.List into 'System.Windows.Documents.List'?
I try to cast the result like this
public List DoctorsList ()
{
// string mainconn = Configuration
List ListOfDoctors;
using (var context = new GlabDbContext())
{
var result = (from c in context.Doctors
select c.LastName).ToList();
**ListOfDoctors = (list)result;**
}
return ListOfDoctors;
}
but I get an error at the run time for the app.
How can I resolve the problem?
Your List ListOfDoctors appears to be really an
System.Windows.Documents.List ListOfDoctors;
and this is also the return type of your method.
Your var result really is
System.Collections.Generic.List<string> result
The two types are not compatible, meaning that you cannot cast one to the other (as the error message says).
I suspect you don't really want to return a Documents.List but a List<string> (containing just those names). So:
Remove a using System.Windows.Documents; from your file
Change all List to List<string>
You can try this like this:
System.Windows.Documents.List listx = new System.Windows.Documents.List();
foreach (var r in result)
{
listx.ListItems.Add(new ListItem(new Paragraph(new Run(r)));
}
Most probably you had an intention to use the IList or List<T>, but accidentally imported the System.Windows.Documents.List and all the later errors appeared because of that.
Please, take a moment and think what return type do you really need and if you want to return a collection of string elements then either use List<string> or IList as a return type:
public IList DoctorsList() // or return List<string> or IList<string> (generic version)
{
// string mainconn = Configuration
IList ListOfDoctors;
using (var context = new GlabDbContext())
{
var result = (from c in context.Doctors
select c.LastName).ToList();
ListOfDoctors = result;
}
return ListOfDoctors;
}
Shorter version (c# 8 compatable):
public IList DoctorsList() // or return List<string> or IList<string> (generic version)
{
using var context = new GlabDbContext();
return (from c in context.Doctors select c.LastName).ToList();
}
Remember:
You can do casting only with compatible types, which means that there should be either appropriate conversion operators defined for both types or a Baseā¶Derived class relationship should exist between types.
For more information:
About Casting and type conversions read here.
About Type conversion operators read here.
I want to convert following to list. I have fetched property using reflection, but how to convert them to list (in my case this is entity object DBSet).
and I need the result as list.
ClassObject.GetType().GetProperty(classname) //After getting property I need it in .ToList()
You can convert with a function like this.
If the reflected object is not enumerable, it can't be converted.
public static List<T> ConvertMysteriousObjectToList<T>(object input)
{
var enumerable = input as IEnumerable;
if (enumerable == null) throw new InvalidOperationException("The object is not convertible to a list.");
return enumerable.Cast<T>().ToList();
}
If you're trying to convert some flavor of DbSet (e.g. a DbSet<Foo>) then you'd call it like this:
var o = ClassObject.GetType().GetProperty(classname);
var list = ConvertMysteriousObjectToList<Foo>(o);
If you don't know the type:
var list = ConvertMysteriousObjectToList<object>(o);
or
var list = ConvertMysteriousObjectToList<dynamic>(o);
I got what I wanted.
static IEnumerable GetAllMembers(DbContext db, string dbSetName)
{
var pi = db.GetType().GetProperty(dbSetName);
return (IEnumerable)pi.GetValue(db);
}
source:
How to get DbSet<SomeClass> (EF) from the dbContext using reflection?
I have the below Linq To SQL Method. When I step through the code spcCodeIDs contains the seven entries I am expecting. However I get a run-time exception of
Method 'Boolean Contains(System.String)' has no supported translation to SQL.
What am I missing?
public static DataTable GetSPCCodeList()
{
using (var context = ProviderDataContext.Create())
{
IQueryable<tblProviderAdminSPCCode> tSPCCode = context.GetTable<tblProviderAdminSPCCode>();
IList<string> spcCodeIDs = BLLCmo.FCApprovedSPCsForGreenSheet();
return (tSPCCode
.Where(spcCode => spcCode.Inactive == null && spcCodeIDs.Contains(spcCode.SPCCodeID))
.OrderBy(spcCode => spcCode.SPCCodeID)
.Select(spcCode => new { spcCode.SPCCodeID, spcCode.SPCDescription, spcCode.SPCCategoryID }))
.CopyLinqToDataTable();
}
}
LINQ to SQL can only support Contains translations form a concrete list and not the IList interface.. try changing your line from
IList<string> spcCodeIDs = BLLCmo.FCApprovedSPCsForGreenSheet();
to
List<string> spcCodeIDs = BLLCmo.FCApprovedSPCsForGreenSheet().ToList();
You need to pass a string as a parameter to Contains. So trying passing spcCode.SPCCodeID.ToString()
ASP.NET 3.5 C#
I am joining two tables using Linq.
Table names are MapAssets and ExitPoint.
In Database they are related with 'has a relationship'
I am writing a function in my BLL to return the joined table
public List<ExitPoints> GetExitPointDetailsByProjectID(int iProjectID)
{
ctx = new CoreDBDataContext();
var exitPointDetails = from ma in ctx.MapAssets
join ep in ctx.ExitPoints
on ma.MapAssetID equals ep.MapAssetID
where ma.ProjectID == iProjectID
select new
{
//would like to have data from both tables here
ctx.MapAssets,
ctx.ExitPoints
};
return exitPointDetails.ToList();
}
This obviuosly doesn't work. And I dont know what to return at all.
All constraint I have for the return is to be able to be bound to a gridview.
is this the correct way? Or else whats the correct way?
You can't, or better, the only way is to return them boxed in a List of object, but this hugely complicates things, because you can't cast them to any type (of course it's anonymous) and you can only access their properties through reflection....
In cases like that, I'd highly suggest you to create a custom class.
EDIT:
On a side note...
If you were using .net 4, things would be easier because you could returns dynamic Type instead of object (look at this link to see dynamic's simplifications), but I'd prefer to create a custom class anyway.
Have a look at how to return anonymous types from Method.
http://forums.asp.net/t/1387455.aspx.
Copying the code from the link.
object ReturnAnonymous()
{
return new { Name="Faisal", City="Chakwal" };
}
// Application entry-point
void Main()
{
object o = ReturnAnonymous();
// This call to 'Cast' method converts first parameter (object) to the
// same type as the type of second parameter - which is in this case
// anonymous type with 'Name' and 'City' properties
var typed = Cast(o, new { Name="", City="" });
Console.WriteLine("Name={0}, City={1}", typed.Name, typed.City);
}
// Cast method - thanks to type inference when calling methods it
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T type)
{
return (T)obj;
}
You can use the method mentioned below to return List and
List<object> lstAnonymousTypes = GetExitPointDetailsByProjectID(1);
foreach(object o in lstAnonymousTypes)
{
//Change it accordingly
var typed = Cast(o, new { new MapAssets() , new ExitPoints() });
}
Hope this helps not tried.
You can't return an anonymous type, you can only use an anonymous type in the scope of the method it's in. You could need to create a new class with MapAssets/ExitPoints properties and select a new instance of that class.
You are trying to return List ExitPoints and List of MapAssets which is not possible because you are getting the output from both tables ie ExitPoints and MapAssets. And it is also not possible to return an anonymous type. So in order to retrun the query create a class name ExMapClass with properties that you need as output of the queries. Now after executing the linq query which you have written iterate it ie
create list of newly created class
list newclass = new list ();
foreach( var result in ctx )
{
instantiate the created class
obj.Property1 = var.MapAssets;
obj.Property2 = var.ExitPoints;
newclass.add(obj);
}
now retrun the list of newlycreated class.
hope you got it.
Do you have to bind to this object after you've created it? If not then you can create an "persistent AnonymousType" class that stores the values in a dictionary and returns the property values with a method like:
string lastName AnonType.GetValue<string>("LastName");
int age AnonType.GetValue<int>("Age");
Here is a link to an excellent example. The author also has an example where he creates the "AnonymousType" from a datatable.
I have worked on a variation of this where I provide the ability to query a list of "AnonymousType" with the following syntax:
// Here's the query
var dept13 = anonAgents.AsQueryable()
.Where(x => x.Has("Department", Compare.Equal, 13);
// Here is how the List is constructed
private static AnonymousType ProvisionAgent(string name, int department)
{
return AnonymousType.Create(new
{
Name = name,
Department = department
});
}
private List<AnonymousType> CreateAnonAgentList()
{
var anonAgents = new List<AnonymousType>();
// Dave and Cal are in Department 13
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Dan Jacobs", 13, 44)));
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Calvin Jones", 13, 60)));
// Leasing = Dept 45
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Stanley Schmidt", 45, 36)));
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Jeff Piper", 45, 32)));
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Stewart Blum", 45, 41)));
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Stuart Green", 45, 38)));
// HR = Dept 21
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Brian Perth", 21, 25)));
anonAgents.Add(AnonymousType.Create(CreateAgentAnonType("Katherine McDonnel", 21, 23)));
return anonAgents;
}
Just use and ArrayList
public static ArrayList GetMembersItems(string ProjectGuid)
{
ArrayList items = new ArrayList();
items.AddRange(yourVariable
.Where(p => p.yourProperty == something)
.ToList());
return items;
}
wont this work ?
ctx = new CoreDBDataContext();
var exitPointDetails = from ma in ctx.MapAssets
join ep in ctx.ExitPoints
on ma.MapAssetID equals ep.MapAssetID
where ma.ProjectID == iProjectID
select Tuple.Create(ma, ep);
return exitPointDetails.ToList();
I have a LINQ statement that returns an anonymous type. I need to get this type to be an ObservableCollection in my Silverlight application. However, the closest I can get it to a
List myObjects;
Can someone tell me how to do this?
ObservableCollection<MyTasks> visibleTasks = e.Result;
var filteredResults = from visibleTask in visibleTasks
select visibleTask;
filteredResults = filteredResults.Where(p => p.DueDate == DateTime.Today);
visibleTasks = filteredResults.ToList(); // This throws a compile time error
How can I go from a anonymous type to an observable collection?
Thank you
As Ekin suggests, you can write a generic method that turns any IEnumerable<T> into an ObservableCollection<T>. This has one significant advantage over creating a new instance of ObservableCollection using constructor - the C# compiler is able to infer the generic type parameter automatically when calling a method, so you don't need to write the type of the elements. This allows you to create a collection of anonymous types, which wouldn't be otherwise possible (e.g. when using a constructor).
One improvement over Ekin's version is to write the method as an extension method. Following the usual naming pattern (such as ToList or ToArray), we can call it ToObservableCollection:
static ObservableCollection<T> ToObservableCollection<T>
(this IEnumerable<T> en) {
return new ObservableCollection<T>(en);
}
Now you can create an observable collection containing anonymous types returned from a LINQ query like this:
var oc =
(from t in visibleTasks
where t.IsSomething == true
select new { Name = t.TaskName, Whatever = t.Foo }
).ToObservableCollection();
Something like this would do the job using type inference features:
private static ObservableCollection<T> CreateObservable<T>(IEnumerable<T> enumerable)
{
return new ObservableCollection<T>(enumerable);
}
static void Main(string[] args)
{
var oc = CreateObservable(args.Where(s => s.Length == 5));
}
You should just be able to do this:
visibleTasks = new ObservableCollection<MyTasks>(filteredResults);
Are you sure that your object is an ObservableCollection indeed? If yes, you can just cast: visibleTasks = (ObservableCollection)filteredResults;
Try:
var filteredResults = from visibleTask in visibleTasks
where(p => p.DueDate == DateTime.Today)
select visibleTask).ToList();
(filteredResults will contain your desired list)