I have to populate below class in Linq Query
public class Emp
{
public string name {get; set;}
public dynamic Obj { get; set; }
public Emp()
{
Obj = new ExpandoObject();
}
}
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = d.DOB,
Obj.BirthPlace = d.BirthPlace
}).ToList();
}
OR
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = new ExpandoObject { DOB = d.DOB, BirthPlace = d.BirthPlace } }).ToList();
}
it doesn't allow me to assign properties dynamically like above, Can anyone please help me how to achieve this?
Try this way:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
It is very similar to #gowansg answer, but without new keyword. It is just setting of values of properties. If we will try to get Type of Obj we will recieve System.Dynamic.ExpandoObject. With new keyword it will be some anonymous type.
respectively, such constructions like:
emp[0].Obj.OtherProperty = 1;
will fail in case of using anonymous type.
You were close in your second example, you just need to set Obj equal to a new anonymous object instead of a new ExpandoObject:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = new { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
Related
I can do var lst = from p in myEntity.tblx --- no problem
instead I want to do something like
List<myClass> lst = from p in myEntity.tblx
where myClass has all the same fields as tblx
I have tried
List<myClass> lst = new List<myClass>();
lst = (from p in myEntity.tblx).ToList();
but that did not work.
say myClass looks like this
class myClass
{
int mainID {get; set;}
string fName {get; set;}
string lName {get; set;}
}
how can I populate
List<myClass> lst from myEntity.tblx
using Linq?
Did you try like below:
List<myClass> lst = (from p in myEntity.tblx
select new myClass()
{
mainID = p.mainID,
fName = p.fname,
lName = p.lName
}).ToList();
Hope this helps!
You are missing projection part
Use
lst = (from p in myEntity.tblx select new myClass()){ mainID = p.mainID, fName = p.fname, lName = p.lName}.ToList();
or
lst = myEntity.tblx.select( p => new myClass() { mainID = p.mainID, fName = p.fname, lName = p.lName}).ToList();
I want to to make a list of the object MyProduct the problem is when i map the child objects to the parent object
My code looks like this
ShopDatabaseEntities db = new ShopDatabaseEntities();
var Result1 = (from Products in db.Products
join ProductProperties in db.ProductProperties on Products.ProductId equals ProductProperties.ProductId
join Properties in db.Properties on ProductProperties.PropertyId equals Properties.PropertyId
select new
{
Products.ProductName,
Products.ProductPrice,
ProductProperties.PropertyValue,
Properties.PropertyName,
ProductProperties.PropertyId
}).ToList();
List<MyProduct> lii = new List<MyProduct>();
foreach (var item in Result1)
{
MyProduct pp = new MyProduct();
pp = (from c in Result1
select new MyProduct { Name = item.ProductName }).First();
MyProperty e = new MyProperty();
e.PropertyName = item.PropertyName;
e.PropertyValue = item.PropertyValue;
pp.pros.Add(e);
lii.Add(pp);
}
It seems to me that this is more what you want:
var query =
from Products in db.Products
join ProductProperties in db.ProductProperties on Products.ProductId equals ProductProperties.ProductId
join Properties in db.Properties on ProductProperties.PropertyId equals Properties.PropertyId
select new
{
ProductProperties.PropertyValue,
Properties.PropertyName,
ProductProperties.PropertyId,
Products.ProductName,
Products.ProductPrice
};
List<MyProduct> lii =
query
.ToArray()
.GroupBy(x => new
{
x.ProductName,
x.ProductPrice
}, x => new
{
x.PropertyValue,
x.PropertyName,
x.PropertyId
})
.Select(x => new MyProduct()
{
Name = x.Key.ProductName,
pros = x
.Select(y => new MyProperty()
{
PropertyName = y.PropertyName,
PropertyValue = y.PropertyValue,
})
.ToList()
})
.ToList();
BTW, this is the code that you should have included in your question to make answering much easier:
public class ShopDatabaseEntities
{
public List<MyProduct> Products = new List<MyProduct>();
public List<MyProductProperty> ProductProperties = new List<MyProductProperty>();
public List<MyProperty> Properties = new List<MyProperty>();
}
public class MyProduct
{
public int ProductId;
public string Name;
public string ProductName;
public decimal ProductPrice;
public List<MyProperty> pros = new List<MyProperty>();
}
public class MyProductProperty
{
public int ProductId;
public int PropertyId;
public double PropertyValue;
}
public class MyProperty
{
public int PropertyId;
public string PropertyName;
public double PropertyValue;
}
Type defs help immensely.
Does any know why I am getting this error when trying to edit something in the database through the ForestLogisticBEAN class?
Cannot implicitly convert type
'System.Collections.Generic.List to
'System.Linq.IQueryable'.
An explicit conversion exists (are you missing a cast?)
Here is the integration layer:
public void EditParcelDetail(ForestLogisticBEAN parcel){
IQueryable<ForestLogisticBEAN> _ForestLogisticsBeans;
_ForestLogisticsBeans = (from order in _context.Orders
from tracking in _context.Trackings
where order.CustomerID == parcel.Id
where tracking.CustomerId == parcel.Id
select new {order.DeliveryDate, order.OrderDate, tracking.Status} ).ToList();
}
Here is the ForestLogisticBEAN class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForestLogistic.Data.BEANS
{
public class ForestLogisticBEAN
{
public int TrackingId { get; set; }
public int OrderId { get; set; }
public bool Status { get; set; }
public DateTime OrderDate { get; set; }
public DateTime DeliveryDate { get; set; }
public ForestLogisticBEAN() { }
}
}
UPDATE:
I changed it to List instead of IQueryable but now it is throwing this error instead
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[ForestLogistics.Data.BEANS.ForestLogisticBEAN]',
but this dictionary requires a model item of type
'ForestLogistics.Data.Order'.
Here is the new integration layer:
public void EditParcelDetail(ForestLogisticBEAN parcel)
{
List<ForestLogisticBEAN> _ForestLogisticsBeans;
_ForestLogisticsBeans = (from order in _context.Orders
from tracking in _context.Trackings
where order.CustomerID == parcel.Id
where tracking.CustomerId == parcel.Id
select new ForestLogisticBEAN {
DeliveryDate = parcel.DeliveryDate,
OrderDate = parcel.OrderDate,
Status = parcel.Status
});
_context.SaveChanges();
}
The aim is to be able to combine the order and the tracking table with the bean class
Enumerable.ToList returns a List<T> which implements IEnumerable<T> and not IQueryable<T>. So you cannot assign it to the IQueryable<ForestLogisticBEAN> variable.
So why don't you declare it as list or IEnumerable?
IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans;
You also have to create instances of ForestLogisticBEAN instead of the anyonymous type that you're selecting. For example:
_ForestLogisticsBeans = (from order in _context.Orders
from tracking in _context.Trackings
where order.CustomerID == parcel.Id
where tracking.CustomerId == parcel.Id
select new ForestLogisticBEAN {
Status = tracking.Status,
OrderDate = order.OrderDate,
DeliveryDate = order.DeliveryDate
}).ToList();
It's clear.
Define:
IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans;
or
List<ForestLogisticBEAN> _ForestLogisticsBeans;
Why you define _ForestLogisticsBeans as IQueryable<ForestLogisticBEAN>? You have defined it as IQueryable and you are assigning List It always give you error.
try var _ForestLogisticsBeans = (from order in _context.Orders....
Or use
IEnumerable<ForestLogisticBEAN> _ForestLogisticsBeans;
Or
List<ForestLogisticBEAN> _ForestLogisticsBeans;
Project in C# and Angular 2+
I am sure this would give result and this could be helpful to others while returning value i get
'System.Collections.Generic.List' to 'System.Collections.Generic.List'
my code is:
List<Ticket> objTicket = new List<Ticket>();
objTicket = ticketRepository.GetAllData().ToList();
List<AccountType> ListAccounType = new List<AccountType>();
ListAccounType = accountTypeRepository.GetAllData().ToList();
List<AccountTransaction> ListAccount = new List<AccountTransaction>();
ListAccount = accountTranastionRepository.GetAllData().ToList();
List<AccountTransactionValue> ListAccountTransactionValue = new List<AccountTransactionValue>();
ListAccountTransactionValue = accountTransactionValueRepository.GetAllData().ToList().Where(o => o.Date >= FromDate && o.Date <= ToDate).ToList();
var ListAccountTransaction = from v in ListAccountTransactionValue
join atr in objTicket on v.AccountTransactionId equals atr.Id
join a in ListAccount on v.AccountId equals a.Id
select new { v.Id, Name = a.Name, v.AccountTransactionId, VoucherNo = atr.Name.Substring(atr.Name.IndexOf("[")), AccountTransactionType = atr.Name.Substring(0, atr.Name.IndexOf("[")), atr.Date, SourceAccountTypeId = atr.Name, Description = atr.CompanyCode, DebitAmount = v.Debit, CreditAmount = v.Credit, atr.DepartmentId };
var ListScreenTicketType = ListAccountTransaction.Select(o => new { o.Id }).Distinct().ToList();
AccountTransactionDocument objAccountTransactionDocument = new AccountTransactionDocument();
if (objAccountTransactionDocument != null)
{
AccountTransactionType objAccountTransactionType = new AccountTransactionType();
}
List<ScreenTicket> listScreenTicket = new List<ScreenTicket>();
foreach (var accounttransaction in ListScreenTicketType)
{
var objaccounttransaction = ListAccountTransaction.Where(o => o.Id == accounttransaction.Id).FirstOrDefault();
ScreenTicket objScreenTicket = new ScreenTicket();
objScreenTicket.Id = accounttransaction.Id;
objScreenTicket.Name = objaccounttransaction.Date.ToShortDateString();
objScreenTicket.Note = objaccounttransaction.Name;
var dataBytes = objaccounttransaction.Name;
if (dataBytes != null)
{
objScreenTicket.IsActive = true;
}
else
{
objScreenTicket.IsActive = false;
}
var objscreens = ListAccountTransaction.Where(o => o.Name == objaccounttransaction.Name);
List<PaymentHistory> listPaymentHistory = new List<PaymentHistory>();
foreach (var screenvalue in objscreens)
{
PaymentHistory objPaymentHistory = new PaymentHistory();
objPaymentHistory.Id = screenvalue.Id;
objPaymentHistory.AmountPaid = screenvalue.CreditAmount;
objPaymentHistory.Id = screenvalue.Id;
listPaymentHistory.Add(objPaymentHistory);
}
objScreenTicket.PaymentHistory = listPaymentHistory;
listScreenTicket.Add(objScreenTicket);
}
return listScreenTicket;
}
I want to convert DataTable with below sample Data
Employee subject1 subject2 subject3 .......
1 100 80 60......
2 90 70 70...
into
List.
Where Employee Object is as follows..
public class Employee
{
public int EmpId { get; set;}
public Dictionary<string,decimal> SubjectMarks;
}
Can anyone help me in converting this Datatable to List in c sharp or using linq.
So the dynamic subject-columns start at index 1 and end at table.Columns-Count-1. Then i would create an array of these columns first. Then you can use Select + ToDictionary + ToList:
DataColumn[] subjectColumns = table.Columns.Cast<DataColumn>().Skip(1).ToArray();
List<Employee> employee = table.AsEnumerable()
.Select(r => new Employee
{
EmpId = r.Field<int>("Employee"),
SubjectMarks = subjectColumns.Select(c => new
{
Subject = c.ColumnName,
Marks = r.Field<decimal>(c)
})
.ToDictionary(x => x.Subject, x => x.Marks)
}).ToList();
Assuming that the type of the columns are already int for the ID and decimal for the marks. Otherwise use int.Parse and decimal.Parse to convert them.
var list = new List<Employee>();
var id = table.Columns[0];
var marks = table.Columns.Cast<DataColumn>().Skip(1).ToArray();
foreach (DataRow row in table.Rows)
{
var obj = new Employee { EmpId = (int) row[id] };
var dict = new Dictionary<string,decimal>();
foreach (var mark in marks)
{
dict[mark.ColumnName] = (decimal)row[mark];
}
obj.SubjectMarks = dict;
list.Add(obj);
}
Instead of using a Dictionary, then you can you List to add subject grades
Try this:
public class Employee
{
public int EmpId { get; set;}
public List<string> SubjectMarks { get; set;}
}
var empList = (from emp in dtEmployeeList.AsEnumerable()
select new Employee()
{
EmpId = (int) emp["Employee"],
SubjectMarks = List<string>()
{
emp["subject1"].ToString(),
emp["subject2"].ToString(),
emp["subject3"].ToString()
}
}).ToList()
You can do like this:
System.Data.DataTable table = // your table
List<Employee> result =
table.AsEnumerable().Select(i => new Employee()
{
EmpId = i.Field<int>("Employee"),
SubjectMarks = { { "subject1", i.Field<decimal>("subject1") } ,
{ "subject2", i.Field<decimal>("subject2") } ,
{ "subject3", i.Field<decimal>("subject3") } }
}).ToList();
You'll need to make sure you have a reference to System.Data.DataSetExtensions. And don't forget to add the using System.Data.
List<PersonsInChargeEntity> picList = new List<PersonsInChargeEntity>();
List<ClientEntity> clientList = new List<ClientEntity>();
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new { ClientNumber = pic.ClientNumber, CompanyName = client.CompanyNameFull, AICGroupID = pic.AICStaffGroupID, RPStaffID = pic.RPStaffID, MPStaffID = pic.MPStaffID, CSPStaffID = pic.CSPStaffID, EQCRStaffID = pic.EQCRStaffID }).ToList<PicList>();
How can i convert my returnList to a List< entity>? below is my class for the entity.
public class PicList
{
int _ClientNumber = 0;
string _CompanyName = "";
int _AICGroupID = 0;
int _RPStaffID = 0;
int _MPStaffID = 0;
int _CSPStaffID = 0;
int _EQCRStaffID = 0;
public PicList()
{
}
public PicList(int ClientNumber, string CompanyName, int AICGroupID, int RPStaffID, int MPStaffID, int CSPStaffID, int EQCRStaffID)
{
_ClientNumber = ClientNumber;
_CompanyName = CompanyName;
_AICGroupID = AICGroupID;
_RPStaffID = RPStaffID;
_MPStaffID = MPStaffID;
_CSPStaffID = CSPStaffID;
_EQCRStaffID = EQCRStaffID;
}
public int ClientNumber
{
get { return _ClientNumber; }
set { _ClientNumber = value; }
}
public string CompanyName
{
get { return _CompanyName; }
set { _CompanyName = value.Trim(); }
}
public int AICGroupID
{
get { return _AICGroupID; }
set { _AICGroupID = value; }
}
public int RPStaffID
{
get { return _RPStaffID; }
set { _RPStaffID = value; }
}
public int MPStaffID
{
get { return _MPStaffID; }
set { _MPStaffID = value; }
}
public int CSPStaffID
{
get { return _CSPStaffID; }
set { _CSPStaffID = value; }
}
public int EQCRStaffID
{
get { return _EQCRStaffID; }
set { _EQCRStaffID = value; }
}
}
From my understanding of your problem, you require the result of the query to be a List<PicList>. To accomplish this, you need to select an instance of the concrete PicList type within your LINQ query rather than of an anonymous type. C# doesn't normally support duck-typing (with some exceptions); in particular, it's not possible to cast one type to another just because the two types happen to have similar property declarations.
I also observe that PicList has a public parameterless constructor, and that all the properties have public setters. So this should work fine:
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new PicList // no longer an anonymous type
{
ClientNumber = pic.ClientNumber,
CompanyName = client.CompanyNameFull,
AICGroupID = pic.AICStaffGroupID,
RPStaffID = pic.RPStaffID,
MPStaffID = pic.MPStaffID,
CSPStaffID = pic.CSPStaffID,
EQCRStaffID = pic.EQCRStaffID
}).ToList();
//ToList<PicList>() is fine but redundant: the generic type argument is inferred.
you are creating an anonymous type here, which can't be casted like you've tried.
try something like:
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new PicList
{
ClientNumber = pic.ClientNumber,
CompanyName = pic.CompanyNameFull,
AICGroupID = pic.AICStaffGroupID,
RPStaffID = pic.RPStaffID,
MPStaffID = pic.MPStaffID,
CSPStaffID = pic.CSPStaffID,
EQCRStaffID = pic.EQCRStaffID
})/*.ToList()*/;
personList = picp.GetPersonsInChargeList(); // got 6000++ records
clientList = (List<ClientEntity>)cp.GetClientList(); // got 5000 ++ records after step thru
//PicList sdf;
var returnList = (from PersonsInChargeEntity pic in personList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select new PicList { ClientNumber = pic.ClientNumber, CompanyName = client.CompanyNameFull, AICGroupID = pic.AICStaffGroupID, RPStaffID = pic.RPStaffID,
MPStaffID = pic.MPStaffID, CSPStaffID = pic.CSPStaffID, EQCRStaffID = pic.EQCRStaffID }).ToList();
but returnList doesnt have any records.
Hmmm, You can do it by very basic method linke this
List<ClientEntity> clientList = new List<ClientEntity>();
var returnList = (from PersonsInChargeEntity pic in picList
join ClientEntity client in clientList
on pic.ClientNumber equals client.ClientNumber
select pic ;
foreach(var item in pic)
{
ClientEntity obj = new ClientEntity();
obj.ClientNumber = item.ClientNumber
......
......
clientList.add(obj);
}
return clientlist;
I hope this will run for you as well