var q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points").**Value.ToString()**;
I would like to get q as a type string after executing this query. Even after keeping the extra bolded line this is giving me some IEnumerable type.
Well let me put it this way. I would like to make the above query something like below one without the runtime throwing any error.
string q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points");
Any help?
var q = (from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points")).FirstOrDefault();
Enumerable.FirstOrDefault Method (IEnumerable)
LINQ will always return an enumerable result. To get it to evaluate and return one result you can use
.First()
.FirstOrDefault()
.Single()
.SingleOrDefault()
depending on your requirement.
The query will return IEnumerable even if the result contains single record. Try this -
if q.count() > 0
var singleQ = q.First();
Or if you are sure that there will be atleast one record then do it like this -
string q = (from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points")).First();
Related
I want to use OR function in my linq query.
Ex:
Sql:
select * from tblusers where userid=1 and status='a' or status='b';
Linq:
var result= _Repository.selectAll().where(x=>x.UserID==1 && x.status=="a" OR x.status=="B");
It's does work for linq query. so does anyone have any idea?
So you are aware about the && operator for comparison, then why not make a try with || operator? Anyway here is the solution for your problem, Following code will get you the result with UserID is 1 and status is either a or B.
_Repository.selectAll().where(x=>x.UserID==1 && (x.status=="a" || x.status=="B"));
Create an array of status you want to check and then use contains. something like this.
var statusList = new[] {"a", "b"};
.Where(x=> x.UserID == 1 && statusList.Contains(x.status));
Adding my 2 cents in here, there is another way you can write your sql query in C# which more or less resembles the sql syntax.
var result = from x in _Repository.SelectAll() where x.UserID == 1 && (x.Status == "a" || x.Status == "B") select x;
This syntax is Query Syntax/Expression where as your snippet is Method Syntax/Expression. Both will achieve same results. Also behind the scene, query syntax is compiled to Method syntax.
At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.
Or other approach with List.Contains, which generates sql query like
SELECT * FROM tblusers WHERE userid=1 AND status IN ('a','b');
var acceptedStatus = new List<string> { 'a', 'b' };
var result= _Repository.selectAll()
.Where(x => x.UserID == 1)
.Where(x => acceptedStatus.Contains(x.Status));
Notice that instead of && operator you can use another Where function and chain them. Can be more readable then fit all conditions in one line.
Try code:
var result =( from x in _Repository.selectAll()
where x.UserID==1 && (x.status=="a" || x.status=="B") select x);
another Solution
var result =( from x in _Repository.selectAll().where(c=>c.status=="a" || x.status=="B")
where x.UserID==1 select x);
I've tried several methods to serach a client who have a propritaire.id in membresEquipeDuClient list, but each time I'm getting the "Invalid 'where' condition. An entity member is invoking an invalid property or method."-error!
I got the error in the second request,
The methods I've used :
List<TeamMembership> membresEquipeDuClient = (from k in context.CreateQuery<TeamMembership>()
where k.teamid == equipeDuClient.Id
select k).ToList();
var pRechercheNumeroClient = (from p in context.CreateQuery<Client>()
where membresEquipeDuClient.Any(a => a.systemuserid == p.proprietaire.Id)
select p).FirstOrDefault();
Any idea how to fix this?
Thx for all the help!
As said in the comment, Any is not supported, but Contains is. So you can do:
var systemUserIds =
(
from k in context.CreateQuery<TeamMembership>()
where k.teamid == equipeDuClient.Id
select k.systemuserid // Select the Id only
).ToList();
var pRechercheNumeroClient =
(
from p in context.CreateQuery<Client>()
where systemUserIds.Contains(p.proprietaire.Id)
select p
).FirstOrDefault();
I'm not familiar with Dynamics CRM, but I think you can remove the ToList from the first statement, so it will be an IQueryable and both statements will be executed as one expression.
var pRechercheNumeroClient = (from p in context.CreateQuery<Client>()
where membresEquipeDuClient.Select(a => a.systemuserid).Contains(p.proprietaire.Id)
select p).FirstOrDefault();
I'm creating a LINQ query that needs to check on the contents before adding something from the list, so what I have is this
var foo = (from f in list1
from p in list1.list2
from m in p.Bar
let t = m.Type
let c = someMethod(t)
where c.Type == type && !foo.Contains(p)
select p).ToList();
the !foo.Contains(p) is not allowed, so is there a way of checking the query as it goes along or before the ToList() should I just add Distinct() to do the same as the condition?
There is no way to access the query as it is being built in the manner you are doing. If you want to ensure that a particular value only appears once in the output then Distinct is the best approach
I have the following linq query:
MyClass myobj = (from p in Session.All<MyClass>()
where p.tags.Split(' ').Contains(searchTag)
select p).FirstOrDefault();
When I run this, I get:
System.NotSupportedException: LINQ to Entities does not recognize the
method 'System.String[] Split(Char[])' method, and this method cannot
be translated into a store expression.
What is a good way to do what I am attempting to do?
The real problem here is the db design, but assuming you have no control over this one idea is to split the query.
First retrieve any rows that contain the search tag anywhere within them.
List<MyClass> myobjs = (from p in Session.All<MyClass>()
where p.tags.Contains(searchTag)
select p).ToList();
Then perform the correct tag search on the retrieved objects in memory.
MyClass myobj = myobjs.FirstOrDefault(m => m.tags.Split(' ').Contains(searchTag));
So, assuming tags = tag1 tag2 tag3, and searchTag is tag2 you can just do:
MyClass myobj = (from p in Session.All<MyClass>()
where p.tags.IndexOf(searchTag) > -1
and searchTag.IndexOf(" ") == -1
select p).FirstOrDefault();
I am trying to mimic below statement in Linq to SQL.
WHERE (rtrim(posid) like '%101' or rtrim(posid) like '%532')
I statement basically determine if posid ends with 101 or 532. In the above example I am only making 2 comparisons but their could be 1 to N comparisons all joined with OR. I store the comparison values (101,532,...) in a generic list that I send to my Linq to SQL method.
I have tried to mimic above SQL using a where clause unsuccessfully (example below):
var PosNum = new List<string>();
PosNum.Add("101");
PosNum.Add("532");
var q = (from a in context.tbl_sspos select a);
q = q.Where(p => PosNum.Contains(p.posid.Trim()));
The issue with the above where clause is that it tries to do an exact match rather I want an ends with comparison.
How would I mimic the SQL statement in Linq to SQL.
Thank You in advance for any help / advice you can provide.
I would use String.EndsWith();
This will check the end of the string rather than entire contents of it.
var q = (from a in context.tbl_sspos select a);
q = q.Where(p => p.posid.EndsWith("102") || p.posid.EndsWith("532"));
In EF 4 you can use the StartsWith / EndsWith methods by now. Might also work in LINQ to SQL.
UPDATE
Just realized that you are trying todo this against multiple values (PosNum), I don't think that this is directly supported currently. You can however concatenate multiple Where()clauses to get the result.
UPDATE 2
As AdamKing pointed out concatenating the where clauses was filtering against all PosNum values, here is the corrected version:
var baseQuery = (from a in context.tbl_sspos select a);
IEnumerable<YourType> q = null;
foreach(var pos in PosNum)
{
if(q == null)
q = baseQuery.Where(a => a.posid.EndsWith(pos));
else
q = q.Union(baseQuery.Where(a => a.posid.EndsWith(pos)));
}
This is not as pretty anymore, but works nonetheless.