Linq:How to write Any in query syntax? - c#

IEnumerable<Gruppe> cand = (IEnumerable<Gruppe>)populations.Where(
x => !x.Attributes.Any(
y => y.GetType() == typeof(Arbeit)
)
);
I wondered how I could write the above in query syntax but stumbled because of the Any method.

There is no equivalent of Any in query syntax. So the best you can do is:
IEnumerable<Gruppe> cand =
from population in populations
where !population.Attributes.Any(y => y.GetType() == typeof(Arbeit))
select population
(I'm assuming that the cast to IEnumerable<Gruppe> is not necessary. If that assumption is wrong, you will need to add it back.)

The Any could be refactored out, but you are still going to need a Count.
var cand = from population in populations
let attributeCount = population.Attributes.Count
let validAttributeCount = (
from attribute in population.Attributes
where attribute.GetType() != typeof(Arbeit)
select attribute
).Count()
where attributeCount == validAttributeCount
select population;

I like Svik's answer.
Another way to put it is like this:
IEnumerable<Gruppe> cand =
from population in populations
where ( from attribute in population.Attributes
where attribute.GetType() == typeof(Arbeit)
select true).Any() == false
select population

Related

Linq to Entities Where clause compare value that can be int or string

I have a drop down list that will provide either a numeric or the word ANY. I need to create a LINQ SELECT containing a WHERE clause that can mimic the following SQL:
var p varchar2(3);
select ... from ...
where (
( (:p = 'ANY') and id in (select distinct id from Ids) )
or
(:p='1' and id = 42)
)
ps: I will be using an expression tree to handle the OR aspect :-)
Somthing like this?
string input = /***/
var result = Context.Entities
.Where(ent => (input == "ANY"
&& Context.UserIds.Select(usr => isr.Id)
.Distinct()
.Contains(ent.Id))
|| (input == "1" && ent.Id == 42))
.Select(ent => /***/);
Disclaimer: written from memory, can contain compile-time errors (typo mistakes etc)

Entity Framework Query Nested Query

I am new to the entity framework and am trying to convert the following query into the correct function calls.
Select Distinct a.nodeId FROM
(SELECT *
FROM reportContents
Where fitId = '29' and reportId =
(select max(reportId)
from reportContents
where fitId = '29')
) a Where (a.nodeId IS NOT NULL)
I know this query does what i want, however i'm not sure how to translate that into the entitiy framework!
Here was my attempt.
var prevSelectedNodes = db.reportContents.Where(
f => f.fitId == id).Select(
f => f.nodeId).Distinct().ToList();
I need to somehow put a .Select() in the where call. However that kind of thing dosen't seem possible
Thank you in advance!
As you can't make two LINQ nested lambda expression. You can do it with two requests :
var maxReportId = db.reportContents.Where(r => r.fitId = "29").Max(r => r.RepordId);
var result = db.reportContents.Where(r => r.fitId == "29" && r.reportId == maxReportId && r.nodeId != null).Select(a => a.nodeId).Distinct().ToList() ;

Where clause in NHibernate

How do I express this in NHibernate?
DECLARE #EntityId INT = 800;
SELECT *
FROM UserAlert
WHERE UserAlertId =
(
SELECT MAX(UserAlertId)
FROM UserAlert
WHERE EntityId = #EntityId
)
This is what I'm trying to do.
var senderUA = session.CreateCriteria<UserAlert>()
.Add(Restrictions.Eq("EntityId", id))
.SetProjection( Projections.Max("Id") )
. UniqueResult();
And I keep getting an error that can convert object to UserAlert type, i.e. it's not even compiling.
Thanks for helping
Ordering by UserAlertId descending and selecting top 1 would be simpler.
var senderUA = session.CreateCriteria<UserAlert>()
.Add(Restrictions.Eq("EntityId", id))
.AddOrder(Order.Desc("UserAlertId"))
.SetMaxResults(1)
.UniqueResult();
Additionally you can
var senderUA = session
.Query<UserAlert>()
.Where(x=>x.EntityId==id &&
x.UserAlertId==session.Query<UserAlert>()
.Where(x=>x.EntiryId==id).Max(x=>x.UserAlertId)
).FirstOrDefault();
Here's a solution using QueryOver.
var maxUserAlertId = QueryOver.Of<UserAlert>
.Where(ua => ua.EntityId == id)
.Select(
Projections.Max(
Projections.Property<UserAlert>
(u => u.UserAlertId)
)
);
var maxUserQuery = session
.QueryOver<UserAlert>()
.WithSubquery
.WhereProperty(u => u.EntityId)
.Eq(maxUserAlertId);
// Dealing with the situation that the maximum value is shared
// by more than one row. If you're certain that it can only
// be one, call SingleOrDefault instead of List
IList<UserAlert> results = maxUserQuery.List();

Linq - Retrieve a single value in a String

I use Asp.net 3.5 and EF 4.
I need find a specific row in my DataBase and display on a label a single value as string.
At the moment I use this code, it is working, so I find a single Object and read its properties.
var myAuthor = (from at in context.CmsAuthors
where at.AuthorId == myRow.AuthorId
select at).Single();
myAuthorNameLabel.Text = myAuthor.LastName;
I would like to know:
If there is another syntax in Linq to achieve the same result.
How to do it using Lamba?
Which approach would you suggest me?
Here's the method syntax (using lambdas)
myAuthorNameLabel.Text = context.CmsAuthors
.Where(at => at.AuthorId == myRow.AuthorId)
.Select(at => at.LastName)
.SingleOrDefault() ?? string.Empty;
You can use:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Single().Select(a => a.LastName);
actually this would be even better:
var myAuthorName =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select(a => a.LastName).Single();
Update
An example of how to use with Anonymous type:
var myAuthorNames =
(from at in context.CmsAuthors where at.AuthorId == myRow.AuthorId select at).Select( a => new {a.LastName, a.FirstName}).Single();

Refractoring a nested query in Linq to Entity Framework

Supposing I have this query:
var ps = from p in dc.Products
let text =
(from t in p.Text
orderby t.Language == "ja" descending
select t).FirstOrDefault()
select new { p.Id, text.Name };
Is there any way to refractor the query being assigned to text?
My guess is that I need to make it an Expression<Func<Product, string, ProductText>>, but I don't know how I'd invoke it.
By the way, if there are more efficient ways to do this, I'd be happy to know.
Thanks,
Rei
Edit: To clarify, the idea is that if Japanese isn't available, I want it to fall back on whatever other language is available.
Maybe this is more efficient?
let text = p.Text.FirstOrDefault(t => t.Language == "ja") ?? p.Text.FirstOrDefault()
Either way, my main question is about how I might make text query reusable -- because it's rather unintuitive, and I can picture myself or someone else doing it wrong in the future.
EDITED BASED ON COMMENT
var ps = dc.Products.Select(p => new
{
Id = p.Id,
Text = p.Text.OrderBy(t=> t.Language == "ja").First()
})
.Select (x => new
{
Id = x.Id,
Name = x.Name,
...
});

Categories