I've been trying to use a lambda for this :
var y = from r in rs.Returns from z in r.Tags where z.Name.Contains(c) select r;
I tried var r = rs.Returns.Where(x=>x.Tags.Where(x=>x.Name.Contains(c)));but it didnt work. What is the correct lambda so I dont have to use y & z
You need a SelectMany to translate the second "from" clause:
var y = rs.Returns
.SelectMany(r => r.Tags, (r, z) => new { r, z })
.Where(pair => pair.z.Name.Contains(c))
.Select(pair => pair.r);
That's a pretty direct translation. Another alternative would be to use:
var y = rs.Returns.Where(r => r.Tags.Any(z => z.Name.Contains(c)));
Related
I have a following code:
var sql = db.Accounts.AsNoTracking()
.Join(db.Customers.AsNoTracking(),
d => d.AccountNr, c => c.CustNr,
(d, c) => new {Accounts = d, Customers = c })
.GroupBy(g => g.Accounts.AccountNr)
.Where(w => w.Accounts.Date == null)
.Select(s => new
{
Company = s.Customers.CompName,
TWQ = s.Customers.TWQ,
AccountNr = s.Accounts.AccountNr,
DocDate = s.Accounts.DocumentDate,
Income = s.Customers.Income
})
.OrderBy(o => o.DocDate);
The issue is that c# underlines the whole WHERE part with an alert saying that: Element IGrouping <string,> has no definition of Accounts and extension method of Accounts can not be found
I don't know where the problem lies. I also tried to use GroupBy in model (instead of using it in the code above) but got the some problem:
var model = (from ss in sql // here I refer to sql outcome I got from the code above
.GroupBy(g => g.AccountNr)
.Skip(page * 15 - 15)
.Take(15)
.AsEnumerable()
select new DocumentsModel
{
Company = s.Customers.CompName,
TWQ = s.Customers.TWQ,
AccountNr = s.Accounts.AccountNr,
DocDate = s.Accounts.DocumentDate,
Income = s.Customers.Income
}).ToList();
At first I would like to say that my English isn't that good.
If you execute an GroupBy, you'll get collection of elements where each element represents a projection over a group and its key.
That's why I execute SelectMany afterwards to work with the model in a normal way.
db.Accounts
.AsNoTracking()
.Join
(
inner: db.Customers.AsNoTracking(),
outerKeySelector: x => x.AccountNr,
innerKeySelector: x => x.CustNr,
resultSelector: (Accounts, Customers) => new
{
Accounts, Customers
}
)
.Where
(
predicate: x => x.Accounts.Date == null
)
.GroupBy
(
keySelector: x => x.Accounts.AccountNr
)
.SelectMany
(
selector: x => x
)
.Select
(
selector: x => new
{
Company = x.Customers.CompName,
TWQ = x.Customers.TWQ,
AccountNr = x.Accounts.AccountNr,
DocDate = x.Accounts.DocumentDate,
Income = x.Customers.Income
}
)
I have a two dimensional array containing objects of type MyObj.
private MyObj[,] myObjs = new MyObj[maxX, maxY];
I want to get the indices from the array when passing in a matching object. I want to get the x and y value from this array. I can return these two values as a Position object that takes a x and y coordinate.
private Position GetIndices(MyObj obj)
{
for (int x = 0; x < myObjs.GetLength(0); x++)
{
for (int y = 0; y < myObjs.GetLength(1); y++)
{
if (myObjs[x, y] == obj)
{
return new Position(x, y);
}
}
}
}
Is it possible to get this code shorten to some Linq code lines?
But I don't think, it looks nice :)
var result = Enumerable.Range(0, myObjs.GetLength(0))
.Select(x => Enumerable.Range(0, myObjs.GetLength(1)).Select(y => new { x, y }))
.SelectMany(o => o)
.FirstOrDefault(o => myObjs[o.x, o.y] == obj);
Here's another option, if you're interested. It uses an indexer inside the first select and does a little math to find where that index falls inside the two-dimensional array.
var o = new MyObj();
myObjs[1,2] = o;
var p = myObjs.Cast<MyObj>()
.Select((x,i) => Tuple.Create(x,i))
.Where(x => x.Item1 == o)
.Select(x => new Point(x.Item2 / myObjs.GetLength(1), x.Item2 % myObjs.GetLength(1)))
.SingleOrDefault();
Console.WriteLine(p); // prints {X=1,Y=2}
It sorta looks like you're considering the x-coordinate to be the height of the array, and the y-coordinate the width, in which case you'd want to switch it up slightly:
var p = myObjs.Cast<MyObj>()
.Select((x,i) => Tuple.Create(x,i))
.Where(x => x.Item1 == o)
.Select(x => new Point(x.Item2 % myObjs.GetLength(1), x.Item2 / myObjs.GetLength(1)))
.SingleOrDefault();
Console.WriteLine(p); // prints {X=2,Y=1}
I used Point instead of Position since it's built into .NET but you should be able to just swap one for the other.
Yes, that is possible. You can ask Resharper to do the job (loop to linq) for you. After installation, just use the feature.
How can I "translate" this SQL query to Linq Lambda Expression:
Select SC.[Description],
COUNT(C.[StatusID]) as Amount
From [StatusCandidate] SC
Left Join
(Select *
From [Candidate] AS c
Where c.RequestID = 1) AS C
ON C.StatusID = SC.StatusCandidateID
Group By SC.[Description];
I try it, But the result is not correct:
dbContext.StatusCandidates
.GroupJoin(
dbContext.Candidates.Where(u => u.RequestID == requestId),
x => x.StatusCandidateID,
y => y.StatusID,
(x, y) => new {x, y})
.GroupBy(g => new {g.x.Description})
.Select(z => new AmountStatus{
StatusName = z.Key.Description,
Amount = z.Count()
}).ToList();
You are pretty close to the desired result: your LINQ makes an inner join, while your SQL has an outer join.
dbContext.StatusCandidates
.GroupJoin(
dbContext.Candidates.Where(u => u.RequestID == requestId)
, x => x.StatusCandidateID
, y => y.StatusID
, (x, y) => new { StatusCandidate = x, StatusGroup = y }
)
.SelectMany(
x => x.StatusGroup.DefaultIfEmpty()
, (x, y) => new { x.StatusCandidate, Status = y}
)
.GroupBy(g => new { g.StatusCandidate.Description })
.Select(z => new AmountStatus{
StatusName = z.Key.Description
, Amount = z.Count()
}).ToList();
Reference: How do you perform a left outer join using LINQ extension methods
If I work with LINQ to Objects, I can use Func<TIn, TOut> in Select, like this:
Enumerable.Range(1, 10).Select(x => new { A = x, B = SomeFunc });
where SomeFunc is something like this:
Func<int, long> SomeFunc = x => x * x;
But working with LINQ to Entities, Func doesn't work, I must use Expression. And this code doesn't work:
var query = Enumerable.Range(1, 10)
.AsQueryable()
.Select(x => new { A = x, B = SomeExpr });
where SomeExpr is something like this:
Expression<Func<int, long>> SomeExpr = x => x * x;
How can I use Expressions in Select in query?
You have to compile and execute the query
var query2 = Enumerable.Range(1, 10)
.AsQueryable()
.Select(x => new { A = x, B = SomeExpr.Compile().DynamicInvoke(x) });
Problem is that x => new {...} is already the expression you pass as an argument to Select(...). Your code will work if you compile and invoke SomeExpr into the select expression.
Expression<Func<int, long>> SomeExpr = x => x * x;
var query = Enumerable.Range(1, 10)
.AsQueryable()
.Select(x => new { A = x, B = SomeExpr.Compile().Invoke(x) });
I've written this code to join two tables together from sql server, now I want to write this as in method syntax. How can I rewrite this code?
LinqToLoginDataContext lnqdore = new LinqToLoginDataContext();
var f = (from k in lnqdore.Table_Years
join h in lnqdore.Table_Dores on k.Id equals h.FK_Year
where h.Id == (int)dataviewDore.CurrentRow.Cells["Id"].Value
select k).Single();
var f = lnqdore.Table_Years
.Join(lnqdore.Table_Dores, k => k.ID, h => h.FK_Year, (k, h) => new { k, h })
.Where(res => res.h.ID == (int)dataviewDore.CurrentRow.Cells["Id"].Value)
.Select(res => res.k)
.Single();