I need to write something that would give the same result as:
var result = collection.Where( o => o.Name.IndexOf( "some_string2" ) != -1 || o.Name.IndexOf( "some_string_2" ) != -1 || o.Name.IndexOf( "some_string3" ) != -1 )
Where the amount and values of the strings to check for (some_string_1, 2 and 3) are unknown (coming from DB), so something more generic...
I tried the following, but failed...
var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();
var result = collection.Where( o => stringsToCheck.Contains( o.ToLower() ) );
In other words, I need to retrieve all the objects from a collection which names contain some specific strings.
var result = collection.Where(item => stringsToCheck.Any(stringToCheck =>
item.Name.Contains(stringToCheck)));
Read in English this is: give me all of the items in the collection where, of all of the strings to check one of them is a substring of the string in the collection.
If you want to test whether o.Name contains a stringToCheck then:
var result = collection.Where( o => stringsToCheck.Any(a => o.Name.Contains(a)));
If you only need to test for equality, then:
var result = collection.Where( o => stringsToCheck.Contains(o.Name));
Note: if you need to apply case normalisation then ToLower() should be applied accordingly.
You are checking the collections element o.ToLower() i assume you must check for its name o.Name.ToLower().
If you want to check whether o.Name contains some string from the stringsToCheck, I would suggest to use LinqKit and build the query with PredicateBuilder.
var predicate = PredicateBuilder.False<TypeOfYourObject>();
var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();
foreach(var str in stringsToCheck)
{
var tmp = str;
predicate = predicate.Or(o=> o.Name.IndexOf(tmp) != -1);
}
resultQuery = collection.Where(predicate);
Related
Why line 2 of mycode can not be read :
var allResarchs = db.Researchs;
allResarchs.Where(a => a.ChiefManagerId == 1);
allResarchs.ToList();
You never set the value of Where statement to the variable.
var allResarchs = db.Researchs.Where(a => a.ChiefManagerId == 1).ToList();
You should assign results of LINQ queries:
var allResarchs = db.Researchs;
var filtered = allResarchs.Where(a => a.ChiefManagerId == 1);
var list = filtered.ToList();
Also you can do it in simplier way (if you do not need intermediate results):
var list = db.Researchs.Where(a => a.ChiefManagerId == 1).ToList();
Linq never changes the input sequence!
allResearches.Where(research => research.ChiefManagerId == 1);
This statement won't change allResearches. You could do the following. (by the way, I've changed the var into the actual returned types, so you understand better what is going on.)
IQueryable<Research> queryResearches = db.Researches;
IQueryable<Research> queryResearchesWithId1 = queryResearches
.Where(research => research.ChiefManagerId == 1);
List<Research> researchesWithId1 = queryResearchedWithId1.ToList();
Be aware, that until the last statement the query is not executed, there is no communication with the database yet. Only the last statement will actually contact the database.
Of course you can write it all in one statement. However, this won't improve performance very much:
var researchesWithId1 = db.Researches
.Where(research => research.ChiefManagerId == 1)
.ToList();
I need to write something that would give the same result as:
var result = collection.Where( o => o.Name.IndexOf( "some_string2" ) != -1 || o.Name.IndexOf( "some_string_2" ) != -1 || o.Name.IndexOf( "some_string3" ) != -1 )
Where the amount and values of the strings to check for (some_string_1, 2 and 3) are unknown (coming from DB), so something more generic...
I tried the following, but failed...
var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();
var result = collection.Where( o => stringsToCheck.Contains( o.ToLower() ) );
In other words, I need to retrieve all the objects from a collection which names contain some specific strings.
var result = collection.Where(item => stringsToCheck.Any(stringToCheck =>
item.Name.Contains(stringToCheck)));
Read in English this is: give me all of the items in the collection where, of all of the strings to check one of them is a substring of the string in the collection.
If you want to test whether o.Name contains a stringToCheck then:
var result = collection.Where( o => stringsToCheck.Any(a => o.Name.Contains(a)));
If you only need to test for equality, then:
var result = collection.Where( o => stringsToCheck.Contains(o.Name));
Note: if you need to apply case normalisation then ToLower() should be applied accordingly.
You are checking the collections element o.ToLower() i assume you must check for its name o.Name.ToLower().
If you want to check whether o.Name contains some string from the stringsToCheck, I would suggest to use LinqKit and build the query with PredicateBuilder.
var predicate = PredicateBuilder.False<TypeOfYourObject>();
var stringsToCheck = someCommaSeparatedStrings.ToLower().Split( ',' ).ToList();
foreach(var str in stringsToCheck)
{
var tmp = str;
predicate = predicate.Or(o=> o.Name.IndexOf(tmp) != -1);
}
resultQuery = collection.Where(predicate);
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();
var j = from c in User.USERs
where (c.USER_NAME.Equals(tempUserName))
select c;
this keeps on giving me an empty sequence
both are just strings im comparing user input with database
Do something like this:
var j = User.USERs.First(c => c.USER_NAME == tempUserName)
or
var j = User.USERs.Single(c => c.USER_NAME == tempUserName)
or just take j[0] from the result your own query gives you.
P.S. - both First or Single will throw an exception if no item matched the query, if you want to get null returned if nothing was found use FirstOrDefault respectively SingleOrDefault.
to broaden the spectrum try something like this:
string userToSearchFor = tempUserName.Trim().ToLower();
var j = User.USERs.FirstOrDefault(c => c.USER_NAME.ToLower() == userToSearchFor);
if (j != null)
{
//found something
}
If it is returning an empty sequence then your where clause is evaluating to false, check what SQL it is generating if you need to solve that problem first.
To answer your question, to get a single element you usually use
.Single()
.SingleOrDefault()
.First()
.FirstOrDefault()
I would do it like this:
var result = User.USERs.SingleOrDefault(x => x.USER_NAME.Equals(tempUserName));
if (result != null)
{
//do your thing
}
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();