LINQ to SQL Storing query results in a variable - c#

For example I am searching for a specific persons ID and I want to store that ID to a local variable or instance variable. How do I retrieve Query results and stores them in a int Variable with LINQ to SQL?
Assuming we have this query
from user in dbo.DoctorsName
where doctorsName = "Foo Bar"
select DOC_ID;

You can use FirstOrDefault() like this:
var results = from user in dbo.DoctorsName
where user.doctorsName == "Foo Bar"
select user;
string personName = results.FirstOrDefault().Name;

This should help.
var name = dbo.DoctorsName.Where(item => item.doctorsName = "Foo Bar").Select(item => item.Name).FirstOrDefault();
If there are no records for your condition then using FirstOrDefault() can throw an exception. For this you can try using -
var namelist = dbo.DoctorsName.Where(item => item.doctorsName = "Foo Bar").Select(item => item.Name);
If(namelist.Count() > 0)
var name = namelist.Fisrt();

Similar to this:
var ticketDepartment = from t in dt_tickets.AsEnumerable()
where t.Field<string>("MID") == mid
select new { department = t.Field<string>("Department") };
and now you have your variable in ticketDepartment.department

Related

C# linq how to get property from predicate list when condition is met

I have the following linq query
var usersToNotify = trainingUsers.Where(x => delegatesToBeReminded.Any(d => d.UserGuid == x.UserGuid))
.Select(x => new RecipientDetail
{
FullName = x.FullName,
Email = x.Email,
// get property from delegatesToBeReminded
})
.ToList();
In the example above, i have trainingusers and delegatesToBeReminded list. i want to retrieve the matching record found in trainingusers and create custom type, with fullname, email from trainingusers and additional property from delegatesTobeReminded.
Can anyone help me how to do this?
Can i use something like this?
var x = from tu in trainingUsers
join d in delegatesToBeReminded on tu.UserGuid equals d.UserGuid
select new RecipientDetail
{
FullName = tu.FullName,
Email = tu.Email,
Session = d.Session
};
Thanks
Easiest would be to use a join, as you suggested:
trainingUsers.Join(
delegatesToBeReminded,
user => user.UserGuid,
delegateToBeReminded => delegateToBeReminded.UserGuid,
(user, delegateToBeReminded) => new RecipientDetail
{
FullName = user.FullName,
Email = user.Email,
Delegate = delegateToBeReminded,
});
(Or you can write the equivalent in linq query syntax, as you did).
Another way is to rewrite this in linq query syntax, using let:
from user in trainingUsers
let delegateToBeReminded = delegatesToBeReminded.FirstOrDefault(d => d.UserGuid == user.UserGuid)
where delegateToBeReminded != null
select new RecipientDetail
{
FullName = user.FullName,
Email = user.Email,
Delegate = delegateToBeReminded,
}
Note that these differ depending on what happens if there is more than one delegate for a particular user. The first creates a new RecipientDetail object for each user/delegate pair; the second creates a RecipientDetail object per user, and picks the first delegate.

dynamically define key name for which the value needs to be identified

I have a keyvalue pair list some thing like this
List<Subscriptions> subs = new List<Subscriptions>();
subs.Add(new Subscriptions() { Id = 1, Name = "ABC" });
subs.Add(new Subscriptions() { Id = 1, Name = "DEF" });
I can search against one key (ID or Name) but what I want to achieve is that user define which key they want to search against ID or Name
right now i am using this approach to filter the list based on Name Value
var filtered = subs.Where(sub => sub.Name.IndexOf(SearchString.Text,StringComparison.OrdinalIgnoreCase) >=0);
sub.Name is defined statically here, I want the user to choose what they want their search to be based on
for example if we have abc:Name program search for abc under Name key and if we have 1:Id then it search for 1 in ID.
This is just an example , in real scenario i can have multiple fields in my list.
I hope I am able to make myself clear.
Why you don't apply the Where by an simple if else or switch
// keyword : abc:Name or 1:Id
var value = keyword.Split(':')[0];
var key = keyword.Split(':')[1];
if(key == "Name")
{
var filterred = subs.Where(sub => sub.Name == value);
}
else if(key == "Id")
var filterred = subs.Where(sub => sub.id == int.Parse(value));
}
Fast answer:
string name = "";
int? id = null;
List<Subscriptions> subs = new List<Subscriptions>();
var query = subs.AsQueryable();
if (!string.IsNullOrEmpty(name))
query = query.Where(p => p.Name == name);
if (id.HasValue)
query = query.Where(p => p.id == id.Value);
var result = query.ToArray();
Detailed answer: you can read about expression tree and IQueryable interface
Basically you can avoid to cast your list to IQueryable if you not use something like Entity Frmework or OData. But if you need to convert you LINQ expression to something more complex - you should use IQueryable, or build your own expression tree.

{"LINQ to Entities does not recognize the method 'Boolean IsLetter(Char)' method, and this method cannot be translated into a store expression."}

I want to get all items in the database using LINQ where the Title starts with special characters or number, I already tried the code below but it's not working.
Thanks
result = (from asset in _db.Query<Asset>()
where !char.IsLetter(asset.Title[0])
select new AssociatedItem { Id = asset.AssetId, Title = asset.Title, Type = Constants.FeedbackTypes.ASSET }).ToList();
That's because char.IsLetter is not a dbFunction.
You can apply where after converting the results ToList()
result = (from asset in _db.Query<Asset>()
select new AssociatedItem { Id = asset.AssetId, Title = asset.Title, Type = Constants.FeedbackTypes.ASSET }).ToList()
.Where(a => !char.IsLetter(a.Title[0])).ToList();
PS: Try to identify some other where clause for the db query to limit the results.
I'd give the SqlMethods class from the System.Data.Linq.SqlClient namespace a shot.
result = (from asset in _db.Query<Asset>()
where !SqlMethods.Like(asset.Title, "[a-Z]%")
select
new AssociatedItem
{
Id = asset.AssetId,
Title = asset.Title,
Type = Constants.FeedbackTypes.ASSET
}).ToList();

Linq query Contains method with where condition with case sensitive less search

I am trying get the data which is contains single word with in the word.Like below query.
List<Models.tbluser> memberslist = new List<Models.tbluser>();
var obct = (from memlist in objcontext.tblusers
where memlist.logname.Contains(member)
select new
{
userid = memlist.userid,
logname = memlist.logname,
decription = memlist.description
}).ToList();
foreach (var item in obct)
{
memberslist.Add(new tbluser
{
userid = item.userid,
logname = item.logname,
description = item.decription
});
}
return Json(memberslist);
But here my problem is i need to search with out case sensitive.
For example
If i search with 'a' i need to get data like Admin,Administrator,User Data.
But i am not getting all these because i am searching with Contains() method.Please let me know how can i get all value either the search value is case sensitive less also.
Change your where condition to be:
memlist.logname.ToUpper().Contains(member.ToUpper())
As a side note, you can shorten your query a bit (you don't need to create an intermediary list):
var memberslist = objcontext.tblusers
.Where(x => x.logname.ToUpper().Contains(member.ToUpper())
.AsEnumerable()
.Select(x => new tbluser
{
userid = x.userid,
logname = x.logname,
decription = x.description
})
.ToList();
return Json(memberslist);
You can change them to Lower or Upper Case when checking the condition using ToLower() or ToUpper():
var obct = (from memlist in objcontext.tblusers
where memlist.logname.ToLower().Contains(member.ToLower())
select new
{
userid = memlist.userid,
logname = memlist.logname,
decription = memlist.description
}).ToList();

Passing parameter to LINQ query

I have a method like below:
public void GetUserIdByCode(string userCode)
{
var query = from u in db.Users
where u.Code == userCode // userCode = "LRAZAK"
select u.Id;
var userId = query.FirstOrDefault(); // userId = 0 :(
}
When I ran the code, I got the default value of 0 assigned to userId meaning the Id was not found.
However, if I changed the userCode with a string like below, I will get the value I want.
public void GetUserIdByCode(string userCode)
{
var query = from u in db.Users
where u.Code == "LRAZAK" // Hard-coded string into the query
select u.Id;
var userId = query.FirstOrDefault(); // userId = 123 Happy days!!
}
My question is why passing the parameter into the LINQ query does not work?
When I stepped into the code, I got the SQL statement like so:
// Does not work...
{SELECT "Extent1"."LOGONNO" AS "LOGONNO"FROM "DEBTORSLIVE"."DEBTORS_LOGONS" "Extent1"WHERE ("Extent1"."LOGONCODE" = :p__linq__0)}
The hard-coded LINQ query (the working one) gives an SQL statement as below:
// Working just fine
{SELECT "Extent1"."LOGONNO" AS "LOGONNO"FROM "DEBTORSLIVE"."DEBTORS_LOGONS" "Extent1"WHERE ('LRAZAK' = "Extent1"."LOGONCODE")}
What would be the solution?
As a work-around, I use Dynamic Linq.
The code below is working for me.
public void GetUserIdByCode(string userCode)
{
string clause = String.Format("Code=\"{0}\"", userCode);
var userId = db.Users
.Where(clause)
.Select(u => u.Id)
.FirstOrDefault();
}
The database query returns an object of User with Code and Id as properties. This is defined in one of my classes.
Here is syntax that will work to pass an argument to a LINQ query.
Not sure how many people will be searching this topic so many years later, but here's a code example that gets the job done:
string cuties = "777";
// string collection
IList<string> stringList = new List<string>() {
"eg. 1",
"ie LAMBDA",
"777"
};
var result = from s in stringList
where (s == cuties)
select s;
foreach (var str in result)
{
Console.WriteLine(str); // Output: "777"
}

Categories