I have a slight issue with some code I'm writing
if(parameter == 1)
{
var linq = from a in db.table select a;
}
else
{
var linq = from a in db.table where a.id = 1 select a;
}
foreach(var b in linq)
{
...
}
So basically what's going on is that the variable "linq" is different depending on the value of "parameter". When I try to loop through "linq" with my foreach loop, I get an error about how linq doesn't exist in the current context.
What is the best way to work around this type of issue?
What you tried doesn't work because the variable linq is already out of scope when you try to use it. You need to move the declaration to the outer scope.
To answer your question in a general way first: if you need to declare a variable before you assign to it, you can't use var. You need to declare the type explicitly:
IQueryable<Something> linq;
if(parameter == 1)
{
linq = from a in db.table select a;
}
else
{
linq = from a in db.table where a.id == 1 select a;
}
In your particular example though you can simplify things:
var query = from a in db.table select a;
if (parameter != 1)
{
query = query.Where(a => a.id == 1);
}
I dunno if this is the best way but, assuming you're returning the same table.
var linq = from a in db.table where a.id = 1 select a;
if(parameter == 1)
{
linq = from a in db.table select a;
}
//foreach.
You can reconstruct your linq query and not pay a big penalty, since you haven't actually executed it.
Related
I'm trying to create a linq query where clause is a constructed variable based on user choices
if (!string.IsNullOrEmpty(txbbox.Text))
{
query = "s.date== DateTime.Parse(txbbox.Text)";
}
if (!string.IsNullOrEmpty(txbbox.Text))
{
query = query + " & (s.type.Contains(txbbox.Text))";
}
there is a way to pass the variable built in the where clause in a LINQ query?
Stemp = (from s in SList
where ***query***
orderby s.DataScadenza
select s).ToList();
Yes; quite simple in this case, actually:
IEnumerable<Whatever> query = SList; // avoid var here, as will impact later assignment
if (!string.IsNullOrEmpty(txbbox.Text))
{
var when = DateTime.Parse(txbbox.Text); // to avoid parsing per item
query = query.Where(s => s.date == when);
}
if (!string.IsNullOrEmpty(txbbox.Text))
{
query = query.Where(s => s.type.Contains(txbbox.Text));
}
Stemp = query.OrderBy(s => s.DateScadenze).ToList();
I have a SQL query that I'm trying to convert to LINQ and am having trouble understanding the obscure error messages when the query is enumerated.
The SQL query (which works as intended), is:
select a.TestGuid, MIN(a.StartTime) as StartTime, COUNT(b.TestCaseId) as NumTests, COUNT(DINSTINCT a.Id) as NumScenarios
from LoadTestSummary as a
join LoadTestTestSummaryData as b
on a.LoadTestRunid = b.LoadTestRunId
where
a.TargetStack = env and
a.TestGuid IS NOT NULL AND
a.StartTime IS NOT NULL AND
a.LoadTestRunId IS NOT NULL
group by a.TestGuid
Converting to LINQ, I get the following:
var q = from a in _context.LoadTestSummary
where
a.TargetStack == env &&
a.TestGuid != null &&
a.StartTime != null &&
a.LoadTestRunId != null
join b in _context.LoadTestTestSummaryData on new
{
LoadTestRunId = Convert.ToInt32(a.LoadTestRunId)
} equals new
{
LoadTestRunId = b.LoadTestRunId
}
group new { a, b } by new
{
a.TestGuid
}
into g
select new
{
DateCreated = g.Min(p => p.a.StartTime),
NumScenarios = g.Count(),
TestGuid = g.Key.TestGuid
NumTests = // ???
};
Two problems I have:
1) When the query is enumerated I get a run-time error that I'm having trouble deciphering. The query works fine in Linqpad, but gives me a run-time error in my program. I am not sure what would cause this. Just staring at this makes my head hurt:
ArgumentException: Expression of type 'System.Func``2[Microsoft.Data.Entity.Query.EntityQueryModelVisitor+TransparentIdentifier``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData],<>f__AnonymousType7``1[System.String]]' cannot be used for parameter of type 'System.Func``2[<>f__AnonymousType5``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData],<>f__AnonymousType7``1[System.String]]' of method 'System.Collections.Generic.IEnumerable``1[System.Linq.IGrouping``2[<>f__AnonymousType7``1[System.String],<>f__AnonymousType5``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData]]] _GroupBy[<>f__AnonymousType5``2,<>f__AnonymousType7``1,<>f__AnonymousType5``2](System.Collections.Generic.IEnumerable``1[<>f__AnonymousType5``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData]], System.Func``2[<>f__AnonymousType5``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData],<>f__AnonymousType7``1[System.String]], System.Func``2[<>f__AnonymousType5``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData],<>f__AnonymousType5``2[PerfPortal.Models.LoadTestSummary,PerfPortal.Models.LoadTestTestSummaryData]])'
2) I am not quite sure how to get the COUNT(DISTINCT a.Id) into the NumTests field. It looks like this isn't supported in LINQ but it looks like other people have asked this question to so I may be able to figure it out once #1 is resolved.
Any thoughts on what's wrong here? I am not even sure exactly what the error is telling me.
All help is appreciated!
Looking just at the SQL query and your LINQ code, I came up with something like this:
from a in LoadTestSummary
join b in LoadTestTestSummaryData
on a.LoadTestRunId equals b.LoadTestRunId
where
a.TargetStack == env &&
a.TestGuid != null &&
a.StartTime != null &&
a.LoadTestRunId != null
group new { a, b } by a.TestGuid into g
select new
{
TestGuid = g.Key,
DateCreated = g.Min(el => el.a.StartTime),
NumTests = g.Select(el => el.b.TestCaseId).Count(),
NumScenarios = g.Select(el => el.a.Id).Distinct().Count()
};
Note, that you don't need to convert LoadTestRunId to int, you may just use standard string comparision.
That horrendous error is most likely caused by grouping and comparing using anonimous objects, thou I prefer not to read that error too much as it's an eldritch abomination not ment to be seen nor comprehend by mere mortals, it seems.
I've got a LINQ query which looks like this:
var query = from produkt in Entity.ProduktCollection.produktCollection
let p = produkt as Entity.Produkt
from version in p.version
let v = version as Entity.Version
from customer in v.customerCollection
let c = customer as Entity.Customer
from fehler in v.fehlerCollection
let f = fehler as Entity.Fehler
where f.id == GetGuid();
select p;
but what I really need is a way to make the f plus its property as well as the p variable, so I might change them to every other possible combination, for example:
where c.name == "frank"
select f;
or
where p.id == GetGuid2()
select c;
Is there any way to achieve this? As far as I know there is no way to insert a switch-case block inside the query between the from/let-part and the where/select-part.
You can create your query in multiple statements because LINQ queries execution is deferred. It applies nicely to different Where statements situation:
var querySource = from produkt in Entity.ProduktCollection.produktCollection
let p = produkt as Entity.Produkt
from version in p.version
let v = version as Entity.Version
from customer in v.customerCollection
let c = customer as Entity.Customer
from fehler in v.fehlerCollection
let f = fehler as Entity.Fehler
select new { p, v, c, f };
if(/* first condition */)
{
querySource = querySource.Where(x => x.f.id == GetGuid());
}
else if(/* second condition */)
{
querySource = querySource.Where(x => x.p.id = 34);
}
var query = querySource.Select(x => x.p);
You can make the Select part conditional as well, but because returned IEnumerable<T> will differ in T part, you won't be able to assign them all to the same variable.
Basically I'm trying to do this in LINQ to SQL;
SELECT DISTINCT a,b,c FROM table WHERE z=35
I have tried this, (c# code)
(from record in db.table
select new table {
a = record.a,
b = record.b,
c = record.c
}).Where(record => record.z.Equals(35)).Distinct();
But when I remove column z from the table object in that fashion I get the following exception;
Binding error: Member 'table.z' not found in projection.
I can't return field z because it will render my distinct useless. Any help is appreciated, thanks.
Edit:
This is a more comprehensive example that includes the use of PredicateBuilder,
var clause = PredicateBuilder.False<User>();
clause = clause.Or(user => user.z.Equals(35));
foreach (int i in IntegerList) {
int tmp = i;
clause = clause.Or(user => user.a.Equals(tmp));
}
var results = (from u in db.Users
select new User {
a = user.a,
b = user.b,
c = user.c
}).Where(clause).Distinct();
Edit2:
Many thanks to everyone for the comments and answers, this is the solution I ended up with,
var clause = PredicateBuilder.False<User>();
clause = clause.Or(user => user.z.Equals(35));
foreach (int i in IntegerList) {
int tmp = i;
clause = clause.Or(user => user.a.Equals(tmp));
}
var results = (from u in db.Users
select u)
.Where(clause)
.Select(u => new User {
a = user.a,
b = user.b,
c = user.c
}).Distinct();
The ordering of the Where followed by the Select is vital.
problem is there because you where clause is outside linq query and you are applying the where clause on the new anonymous datatype thats y it causing error
Suggest you to change you query like
(from record in db.table
where record.z == 35
select new table {
a = record.a,
b = record.b,
c = record.c
}).Distinct();
Can't you just put the WHERE clause in the LINQ?
(from record in db.table
where record.z == 35
select new table {
a = record.a,
b = record.b,
c = record.c
}).Distinct();
Alternatively, if you absolutely had to have it the way you wrote it, use .Select
.Select(r => new { a = r.a, b=r.b, c=r.c }).Distinct();
As shown here LINQ Select Distinct with Anonymous Types, this method will work since it compares all public properties of anonymous types.
Hopefully this helps, unfortunately I have not much experience with LINQ so my answer is limited in expertise.
Consider this:
var query = from r in this._db.Recipes
where r.RecipesID == recipeID
select new { r.RecipesID, r.RecipesName };
How would i get individual columns in my query object without using a for-loop?
Basicly: how do I translate DataTable.Rows[0]["ColumnName"] into Linq syntax?
It's really unclear what you are looking for, as your two samples are compatible.
As close as I can figure, what you want is:
var rows = query.ToList();
string name = rows[0].RecipesName;
string name = this._db.Recipes.Single(r => r.RecipesID == recipeID).RecipesName;
This is the way to go about it:
DataContext dc = new DataContext();
var recipe = (from r in dc.Recipes
where r.RecipesID == 1
select r).FirstOrDefault();
if (recipe != null)
{
id = recipe.RecipesID;
name = recipe.RecipesName;
}
Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:
query.First().ColumnName
or if you want to avoid an exception on empty list:
var obj = query.FirstOrDefault();
if (obj != null)
obj.ColumnName;
Original Answer (so the comment makes sense):
Use Linq to Datasets. Basically would be something like:
var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");