i have some problems with my c# code everywhere in the Examples they do it like me but somehow i gonna get some errors
Compiler says at g.Datum he doesn' t know Datum
and at "return query" he says - cannot convert, there is a explicit convert
var query = (from p in dataContext.Untersuchungen
orderby p.Datum
group p by p.Datum into g
let number = (from n in dataContext.Untersuchungen
where n.Datum == g.Datum
select n).Count()
select new StatsistikObjekt() { Date1 = g.Datum, number1 = number });
return query;
hope you can help me =)
The type of the range variable g is the group, which indeed doesn't have a Datum value.
You can fix that bit easily, given your grouping (which uses Datum as the key)- and make your query simpler too by just counting the size of the group:
var query = (from p in dataContext.Untersuchungen
orderby p.Datum
group p by p.Datum into g
select new StatsistikObjekt() { Date1 = g.Key,
number1 = g.Count() });
As for the return value - we can't really help you on that one, as we don't know the return type you're trying to return.
Try
g.Key instead of g.Datum
Related
Good day. I have a Linq code that when run, shows this error
Invalid length parameter passed to the LEFT or SUBSTRING function.
But when I try to put all the same values into SQL, it works fine. Is there something wrong with my LINQ code?
THE OUTPUT IN SQL
OUTPUT
CODE
var list = (from R in db.vwEtracs_Receipt
join RI in db.vwEtracs_ReceiptItem on R.objid equals RI.parentid
join IA in db.vwEtracs_IncomeAccount on RI.acctid equals IA.objid
join M in db.vwtbl_Motor
on new { motor_no = R.remarks.Substring(5), operator_id = R.payerId }
equals new { motor_no = M.motor_no, operator_id = M.operator_id } into M_join
from M in M_join.DefaultIfEmpty()
join F in db.tbl_Franchise on R.objid equals F.or_id into F_join
from F in F_join.DefaultIfEmpty()
join B in db.tbl_Make on M.brand_id equals B.id
where
IA.objid == "FTFA00000238" &&
R.voidId == null &&
R.remarks != null
orderby R.txndate descending
select new PayedViewModel
{
application_no = F.application_no,
remarks = R.remarks,
serialno = R.serialno,
payername = R.payername,
payeraddress = R.payeraddress,
motor_no = M.motor_no,
chassis_no = M.chassis_no,
plate_no = M.plate_no,
brand_name = B.Make,
motor_id = M.motor_id,
year = R.txndate.Value.Year.ToString(),
mtop = F.mtop,
franchise_id = F.franchise_id
}
).Distinct();
Usually the error shows in this line, motor_no = R.remarks.Substring(5) because when I change it to 4, the code runs smoothly. I tried manually checking all the data in the db but found nothing suspicious nor anything that will give it negative value.
At this point I don't know what is wrong with my code or db. Thank you.
It may happen because your database have string which it's length less than 5
make sure that all R.remarks.length are more than 5
may be you need to do check or something like this :
R.remarks.Length > 5 ? R.remarks.Substring(5) : R.remarks
I have the below code to return a list of strings.
public List<string> Top5CodesForToday()
{
var date = DateTime.Now;
var resultList = new List<string>();
using (var db = new PillowContext())
{
var qry = (from d in db.DownTimes
where DbFunctions.TruncateTime(d.DateTime) == DbFunctions.TruncateTime(date)
group d by new {d.Code}
into g
let total = g.Sum(x => x.Amount)
orderby total descending
let top5 = g.Take(5).ToList()
select new {g.Key.Code, Total = total});
foreach (var item in qry)
{
int x = item.Code;
var results = from r in db.DownTimeCodes
where r.Code == x
select r.Description;
resultList.Add(results.ToString());
}
}
return resultList;
}
When I look at the contents of returnList I am seeing the correct number of items however each item is made up of the actual query syntax, not the data itself. I have seen this before and usually solve it by doing .ToList() however I am unsure how I could change my code to solve this
The problem here is that when you are calling ToString the query is not executed yet, so essentially you are calling ToString on a IQueryable object, receiving the query instead of results. You need to call something to execute the query.
You can call ToList() still:
var results = (from r in db.DownTimeCodes
where r.Code == x
select r.Description).ToList();
resultList.AddRange(results);
Or, if you expect just one result, call FirstOrDefault()/SingleOrDefault():
var results = (from r in db.DownTimeCodes
where r.Code == x
select r.Description).FirstOrDefault();
resultList.Add(results);
You are calling ToString() on List<>. As default for most complex types, it just writes out type name not the data.
This line
resultList.Add(results.ToString());
should be changed to
resultList.AddRange(results);
I am trying to write dynamic Linq Library query to fetch record on condition,
Customers who has order count is greater than 3 and ShipVia field equal 2.
Below is my syntax what i have tried.
object[] objArr = new object[10];
objArr[0] = 1;
IQueryable<Customer> test = db.Customers.Where("Orders.Count(ShipVia=2)", objArr);
and
IQueryable<Customer> test = db.Customers.Where("Orders.Any(ShipVia=2).Count()", objArr);
But both are not working. In second query Any returns true so it won't work with Count.
Suggest me a way to implement this.
If you HAVE to use Dynamic Linq, your query should look like that:
db.Customers.Where("Orders.Count(ShipVia == 2) > 3");
How about something like this.
IQueryable<Customer> test = db.Customers.Where(c => c.Orders.Where(o => o.ShipVia ==2).Count() >2);
var grp = db.Customers.Where("ShipVia=2").GroupBy("ShipVia");
var test = from a in grp
where a.Count() > 3
select a.Key;
IQueryable<Customer> test =
from c in db.Customers
from o in c.Orders
where o.ShipVia == 2 // NOTE you need == not = for compare
group c by c into grp
select new {customer = grp.key, ordercount = grp.Count() };
Untested but I believe this should do it all in one statement, assuming Orders are a collection within Customer.
Note that your single = in your where clause is very dangerous as it'll assign 2 to all shipvias instead of test (==)
I have a small problem in my where clause in the linq expression below. If I put the number 3 instead of department.Id I get the desired result but when I use department.Id I get nothing in the resultset.
I also want to get a count for the number of filters for that filter name using the query again using distinct.
var dept = Page.RouteData.Values["department"];
var department = (from d in db.Departments
where d.Name.Replace(" ", "-") == dept
select new {d.Id, d.Name}).FirstOrDefault();
var query = from p in db.Products
join f in db.ProductFilters on p.Id equals f.ProductId into filters
from x in filters.Where(x => x.Product.DepartmentId == department.Id
/* if == 3 it works */)
select new { x.Name, x.Id };
Promoted to answer from comments:
Have you checked that the department instance is as you think it should be after the first linq statement - ie has an Id == 3?
Your first query is not finding any valid department and is therefore returning default which most probably means that departmend.Id == 0.
I am having a terrible time finding a solution to what I am sure is a simple problem.
I started an app with data in Lists of objects. It's pertinent objects used to look like this (very simplified):
class A {
int[] Nums;
}
and
List<A> myListOfA;
I wanted to count occurrences of values in the member array over all the List.
I found this solution somehow:
var results
from a in myListOfA
from n in a.Nums
group n by n into g
orderby g.Key
select new{ number = g.Key, Occurences = g.Count}
int NumberOfValues = results.Count();
That worked well and I was able to generate the histogram I wanted from the query.
Now I have converted to using an SQL database. The table I am using now looks like this:
MyTable {
int Value1;
int Value2;
int Value3;
int Value4;
int Value5;
int Value6;
}
I have a DataContext that maps to the DB.
I cannot figure out how to translate the previous LINQ statement to work with this. I have tried this:
MyDataContext myContext;
var results =
from d in myContext.MyTable
from n in new{ d.Value1, d.Value2, d.Value3, d.Value4, d.Value5, d.Value6 }
group n by n into g
orderby g.Key
select new { number = g.Key, Occurences = g.Count() };
I have tried some variations on the constructed array like adding .AsQueryable() at the end - something I saw somewhere else. I have tried using group to create the array of values but nothing works. I am a relative newbie when it come to database languages. I just cannot find any clue anywhere on the web. Maybe I am not asking the right question. Any help is appreciated.
I received help on a microsoft site. The problem is mixing LINQ to SQL with LINQ to Objects.
This is how the query should be stated:
var results =
from d in MyContext.MyTable.AsEnumerable()
from n in new[]{d.Value1, d.Value2, d.Value3, d.Value4, d.Value5, d.Value6}
group n by n into g
orderby g.Key
select new {number = g.Key, Occureneces = g.Count()};
Works like a charm.
If you wish to use LINQ to SQL, you could try this "hack" that I recently discovered. It isn't the prettiest most cleanest code, but at least you won't have to revert to using LINQ to Objects.
var query =
from d in MyContext.MyTable
let v1 = MyContext.MyTable.Where(dd => dd.ID == d.ID).Select(dd => dd.Value1)
let v2 = MyContext.MyTable.Where(dd => dd.ID == d.ID).Select(dd => dd.Value2)
// ...
let v6 = MyContext.MyTable.Where(dd => dd.ID == d.ID).Select(dd => dd.Value6)
from n in v1.Concat(v2).Concat(v3).Concat(v4).Concat(v5).Concat(v6)
group 1 by n into g
orderby g.Key
select new
{
number = g.Key,
Occureneces = g.Count(),
};
How about creating your int array on the fly?
var results =
from d in myContext.MyTable
from n in new int[] { d.Value1, d.Value2, d.Value3, d.Value4, d.Value5, d.Value6 }
group n by n into g
orderby g.Key
select new { number = g.Key, Occurences = g.Count() };
In a relational database, such as SQL Server, collections are represented as tables. So you should actually have two tables - Samples and Values. The Keys table would represent a single "A" object, while the Values table would represent each element in A.Nums, with a foreign key pointing to the one of the records in the Samples table. LINQ to SQL
's O/R mapper will then create a "Values" property for each Sample object, which contains a queryable collection of the attached Values. You would then use the following query:
var results =
from sample in myContext.Samples
from value in sample.Values
group value by value into values
orderby values.Key
select new { Value = values.Key, Frequency = values.Count() };