I want to create a dynamic query with LINQ-to-SQL and everything works except for one thing: group by. I looked at the other questions but haven't found a reason so far why it does not work.
I use using System.Linq.Dynamic; with the following query (that works):
int numberOfRankedItems = 3;
string minMaxChoice = "max";
string orderBy = "";
if (minMaxChoice == "max")
{
orderBy = "queryGroup.Sum(row => row.POSITIONVALUE) descending";
} else if (minMaxChoice == "min")
{
orderBy = "queryGroup.Sum(row => row.POSITIONVALUE) ascending";
}
string minMaxFeatureColumnName = "BRANDNAME";
string selectMinMaxFeature = "new { minMaxFeature = queryGroup.Key." + minMaxFeatureColumnName + ", sumPosition = queryGroup.Sum(row => row.POSITIONVALUE)}";
var query = (from tableRow in Context.xxx
where /* some filters */
group tableRow by tableRow.BRANDNAME into queryGroup
orderby orderBy
select selectMinMaxFeature).Take(numberOfRankedItems).ToList();
The use of variables for orderby and select works fine, but for group by not no matter what I try to replace with a variable. The query actually works if I e.g. use a variable instead of tableRow.BRANDNAME but the query returns the wrong result. The goal is to be able to set the column for the grouping dynamically.
Ideas?
Thanks
Edit: there seem to be multiple issues also with the other variables. So I generalize the question a bit: how can I generalize the following query in terms of
The column to group by
The column to order by + ASC or DESC
In the select statement the columnname of the first statement (BRANDNAME)
Here is the query:
var query = (from tableRow in ctx.xxx
where /* filter */
group tableRow by new { tableRow.BRANDNAME } into queryGroup
orderby queryGroup.Sum(row => row.POSITIONVALUE) descending
select new { minMaxFeature = queryGroup.Key.BRANDNAME, sumPosition = queryGroup.Sum(row => row.POSITIONVALUE) }).Take(numberOfRankedItems).ToList();
Would be great without expression trees ;)
I have now elaborated a solution to the question:
The solution uses as before using System.Linq.Dynamic; allows now to set certain variables. In the end it returns a dictionary.
// set variables
int numberOfRankedItems;
if (queryData.NumberOfRankedItems != null)
{
numberOfRankedItems = (int) queryData.NumberOfRankedItems;
} else
{
numberOfRankedItems = 0;
}
string minMaxChoice = queryData.MinMaxChoice;
string minMaxFeatureColumnName = queryData.MinMaxFeatureColumnName;
string orderByPrompt = "";
if (minMaxChoice == "max")
{
orderByPrompt = "it.Sum(POSITIONVALUE) descending";
} else if (minMaxChoice == "min")
{
orderByPrompt = "it.Sum(POSITIONVALUE) ascending";
}
string groupByPrompt = queryData.MinMaxFeatureColumnName;
// execute query
IQueryable query = (from tableRow in Context.xxx
where /* some filters */
select tableRow).
GroupBy(groupByPrompt, "it").
OrderBy(orderByPrompt).
Select("new (it.Key as minMaxFeature, it.Sum(POSITIONVALUE) as sumPosition)").
Take(numberOfRankedItems);
// create response dictionary
Dictionary<int?, Dictionary<string, int?>> response = new Dictionary<int?, Dictionary<string, int?>>();
int count = 1;
foreach (dynamic item in query)
{
string minMaxFeatureReturn = item.GetType().GetProperty("minMaxFeature").GetValue(item);
int? sumPositionReturn = item.GetType().GetProperty("sumPosition").GetValue(item);
response[count] = new Dictionary<string, int?>() { { minMaxFeatureReturn, sumPositionReturn } };
count++;
}
return response;
Related
This question already has answers here:
Linq to Entities - SQL "IN" clause
(9 answers)
Closed 8 years ago.
How to make a where in clause similar to one in SQL Server?
I made one by myself but can anyone please improve this?
public List<State> Wherein(string listofcountrycodes)
{
string[] countrycode = null;
countrycode = listofcountrycodes.Split(',');
List<State> statelist = new List<State>();
for (int i = 0; i < countrycode.Length; i++)
{
_states.AddRange(
from states in _objdatasources.StateList()
where states.CountryCode == countrycode[i].ToString()
select new State
{
StateName = states.StateName
});
}
return _states;
}
This expression should do what you want to achieve.
dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
This will translate to a where in clause in Linq to SQL...
var myInClause = new string[] {"One", "Two", "Three"};
var results = from x in MyTable
where myInClause.Contains(x.SomeColumn)
select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));
In the case of your query, you could do something like this...
var results = from states in _objectdatasource.StateList()
where listofcountrycodes.Contains(states.CountryCode)
select new State
{
StateName = states.StateName
};
// OR
var results = _objectdatasource.StateList()
.Where(s => listofcountrycodes.Contains(s.CountryCode))
.Select(s => new State { StateName = s.StateName});
I like it as an extension method:
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
Now you call:
var states = _objdatasources.StateList().Where(s => s.In(countrycodes));
You can pass individual values too:
var states = tooManyStates.Where(s => s.In("x", "y", "z"));
Feels more natural and closer to sql.
public List<Requirement> listInquiryLogged()
{
using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
var result = from Q in dt.Requirements
where inq.Contains(Q.ID)
orderby Q.Description
select Q;
return result.ToList<Requirement>();
}
}
The "IN" clause is built into linq via the .Contains() method.
For example, to get all People whose .States's are "NY" or "FL":
using (DataContext dc = new DataContext("connectionstring"))
{
List<string> states = new List<string>(){"NY", "FL"};
List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();
}
from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state
This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.
Problem:
Let say we have document table. Schema as follows
schema : document(name,version,auther,modifieddate)
composite Keys : name,version
So we need to get latest versions of all documents.
soloution
var result = (from t in Context.document
where ((from tt in Context.document where t.Name == tt.Name
orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
select t).ToList();
public List<State> GetcountryCodeStates(List<string> countryCodes)
{
List<State> states = new List<State>();
states = (from a in _objdatasources.StateList.AsEnumerable()
where countryCodes.Any(c => c.Contains(a.CountryCode))
select a).ToList();
return states;
}
I need some help to calculate a property inside my Linq query.
I know I need to use "let" somewhere, but I can't figure it out!
So, first I have this method to get my list from Database:
public BindingList<Builders> GetListBuilders()
{
BindingList<Builders> builderList = new BindingList<Builders>();
var ctx = new IWMJEntities();
var query = (from l in ctx.tblBuilders
select new Builders
{
ID = l.BuilderID,
Projeto = l.NomeProjeto,
Status = l.Status,
DataPedido = l.DataPedido,
DataPendente = l.DataPendente,
DataEntregue = l.DataEntregue,
DataAnulado = l.DataAnulado
});
foreach (var list in query)
builderList.Add(list);
return builderList;
}
Then, I have a function to calculate the Days between Dates accordingly to Status:
public int GetDays()
{
int Dias = 0;
foreach (var record in GetListBuilders)
{
if (record.Status == "Recebido")
{
Dias = GetBusinessDays(record.DataPedido, DateTime.Now);
}
else if (record.Status == "Pendente")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataPendente);
}
else if (record.Status == "Entregue")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataEntregue);
}
else if (record.Status == "Anulado")
{
Dias = GetBusinessDays(record.DataPedido, (DateTime)record.DataAnulado);
}
}
return Dias;
}
I need to call the GetDays in a DataGridView to give the days for each record.
My big problem is, How do I get this? include it in Linq Query? Calling GetDays() (need to pass the ID from each record to GetDays() function)!?
Any help?
Thanks
I think it would be easier to create an extension method:
public static int GetBusinessDays(this Builders builder) // or type of ctx.tblBuilders if not the same
{
if (builder == null) return 0;
switch(builder.status)
{
case "Recebido": return GetBusinessDays(builder.DataPedido, DateTime.Now);
case "Pendente": return GetBusinessDays(builder.DataPedido, (DateTime)builder.DataPendente);
case "Entregue": return GetBusinessDays(builder.DataPedido, (DateTime)builder.DataEntregue);
case "Anulado": GetBusinessDays(builder.DataPedido, (DateTime)builder.DataAnulado);
default: return 0;
}
}
Then, call it like that:
public BindingList<Builders> GetListBuilders()
{
BindingList<Builders> builderList = new BindingList<Builders>();
var ctx = new IWMJEntities();
var query = (from l in ctx.tblBuilders
select new Builders
{
ID = l.BuilderID,
Projeto = l.NomeProjeto,
Status = l.Status,
DataPedido = l.DataPedido,
DataPendente = l.DataPendente,
DataEntregue = l.DataEntregue,
DataAnulado = l.DataAnulado,
Dias = l.GetBusinessDays()
});
foreach (var list in query)
builderList.Add(list);
return builderList;
}
To do better, to convert a object to a new one, you should create a mapper.
Why does it need to be a part of the query? You can't execute C# code on the database. If you want the calculation to be done at the DB you could create a view.
You're query is executed as soon as the IQueryable is enumerated at the foreach loop. Why not just perform the calculation on each item as they are enumerated and set the property when you are adding each item to the list?
Sort in LINQ
I have 2 database CustomerEntities and BillEntities
I want to get CustomerName from CustomerEntities and sort it but it have no data and I want .ToList() just once time because it slow if used many .ToList()
using (var db1 = new CustomerEntities())
{ using (var db2 = new BillEntities())
{
var CustomerData = db1.Customer.Select(s=> new{s.CustomerCode,s.CustomerName}).ToList();
var BillData = (from t1 in db2.Bill
select new {
BillCode = t1.Billcode,
CustomerCode = t1.Customer,
CustomerName = ""; //have no data
});
}
if(sorting.status==true)
{
BillData= BillData.OrderBy(o=>o.CustomerName); //can't sort because CustomerName have no data
}
var data = BillData .Skip(sorting.start).Take(sorting.length).ToList(); // I want .ToList() just once time because it slow if used many .ToList()
foreach (var b in data)
{
var Customer = CustomerData.FirstOrDefault(f => f.CustomerCode==b.CustomerCode );
if(CustomerName>!=null)
{
r.CustomerName = Customer.CustomerName; //loop add data CustomerName
}
}
}
I have no idea to do it. Help me please
I'm not sure if I understand your code but what about this:
var BillData = (from t1 in db2.Bill
select new {
BillCode = t1.Billcode,
CustomerCode = t1.Customer,
CustomerName = db1.Customer.FirstOrDefault(c => c.CustormerCode == t1.Customer)?.CustomerName
});
Then you have objects in BillData that holds the CustomerName and you can order by that:
BillData.OrderBy(bd => bd.CustomerName);
If you just want to get CustomerName from your customer Db and sort it, this is what i would have used. I used orderByDescending but you can use OrderBy aswell.
public List<Customer> getLogsByCustomerName(string customername)
{
using (var dbentites = new CustomerEntities())
{
var result = (from res in dbentites.Customer.OrderByDescending(_ => _.CustomerName)
where res.CustomerName == customername
select res).ToList();
return result.ToList();
}
}
i want to get count in linq query its work fine without comparing date in where condition but after comparing date it gives exception.
public static IList GetAllCategoryData()
{
using (var objEntity = new BlueCouponEntities())
{
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > DateTime.Now.Date).Count(),
}
).ToList();
}
}
Error is : The specified type member ;Date; is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
You have to use EntityFunctions.TruncateTime to get the Date part of DateTime
using (var objEntity = new BlueCouponEntities())
{
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > EntityFunctions.TruncateTime(DateTime.Now)).Count(),
}
).ToList();
}
Since DateTime.Now is Constant at the moment, you could also write this
using (var objEntity = new BlueCouponEntities())
{
DateTime now = DateTime.Now.Date;
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && Lg.OfferMaster.EndDate > now).Count(),
}
).ToList();
}
It has nothing to do with the Count() function. As the exception says, its
a DateTime problem. Use DbFunctions.TruncateTime (EntityFunctions.TruncateTime is deprecated since EF6)
public static IList GetAllCategoryData()
{
using (var objEntity = new BlueCouponEntities())
{
return (from TBL in objEntity.CategoryMasters.AsEnumerable()
let IIT = TBL.CategoryImageTransactions
select new
{
TBL.CategoryID,
TBL.CategoryName,
CategoryCount = objEntity.OfferCategoryMasters.Where(Lg => Lg.CategoryID == TBL.CategoryID && EntityFunctions.TruncateTime(Lg.OfferMaster.EndDate) > EntityFunctions.TruncateTime(DateTime.Now.Date)).Count(),
}
).ToList();
}
}
Add following lines:
var today = DateTime.Now.Date;
Then use today instead of DateTime.Now.Date into linq query.
I am using the below logic to merge List rows in a list together if they have all have identical columns apart from one (OtherAuditeesUserName). In which case i join the different values of OtherAuditeesUserName with a comma seperater
The original list looks like this:
TrailRemarkId,PreviousAudit,OtherAuditees,StrategicPriority,Observations,DocumentsReviewed
1,"old audit","jane smith", 1,none, doc.docx
1,"old audit","john collins", 1,none, doc.docx
The end result I am looking for is :
TrailRemarkId,PreviousAudit,OtherAuditees,StrategicPriority,Observations,DocumentsReviewed
1,"old audit","jane smaith, john collins", 1,none, doc.docx
see how OtherAuditees is joined using a comma.
Can someone point out a more efficient way to merge List rows ?
var trailRemarks = (from a in auditData
select new
{
a.TrailRemarkId,
a.PreviousAudit,
a.OtherAuditees,
a.StrategicPriority,
a.Observations,
a.DocumentsReviewed,
}).Distinct();
List<TrailRemarkEntity> trlist = new List<TrailRemarkEntity>() ;
int? trId = 0;
foreach (var tr in trailRemarks)
{
if (trId == 0 || (trId != tr.TrailRemarkId))
{
trlist.Add(
new TrailRemarkEntity()
{
TrailRemarkId = tr.TrailRemarkId ?? 0,
PreviousAuditName = tr.PreviousAudit,
DocumentsReviewed = tr.DocumentsReviewed,
StrategicPriorityName = tr.StrategicPriority,
OtherAuditeesUserName = tr.OtherAuditees,
Observations = tr.Observations
}
);
}
else
{
var existingTR = trlist.Last();
existingTR.OtherAuditeesUserName += ", " + tr.OtherAuditees;
}
trId = tr.TrailRemarkId;
}
You can use group by and string.join for doing it like below,
List<TrailRemarkEntity> trailRemarks = (from a in auditData
group a by new {
a.TrailRemarkId,
a.TrailRemarkId,
a.PreviousAudit,
a.StrategicPriority,
a.Observations,
a.DocumentsReviewed
} into groupedData
select new TrailRemarkEntity()
{
TrailRemarkId = groupedData.Key.TrailRemarkId ?? 0,
PreviousAuditName = groupedData.Key.PreviousAudit,
DocumentsReviewed = groupedData.Key.DocumentsReviewed,
StrategicPriorityName = groupedData.Key.StrategicPriority,
OtherAuditeesUserName = string.join("," , groupedData.Select(exp=>exp.OtherAuditees)),
Observations = groupedData.Key.Observations
}).ToList();
Hope it helps.
Thanks thisiva, your solution worked but I modified it slightly to remove duplicates as follows:
string.Join(",", groupedData.Select(exp => exp.OtherAuditees).Distinct())