Linq query Contains method with where condition with case sensitive less search - c#

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();

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.

C# linq lambda join and select syntax

I'm looking for the counterpart of Msql query:
SELECT per.*,add.addressDescription FROM Persons per
JOIN Address add ON per.AddressId = add.AddressId
I have this query:
var query = persons.JOIN(address,per = person.addressId,add = addressId
(per,add) =>
new Persons{
addressDescription = add.addressDescription,
PersonId = per.PersonId,
PersonFirstName = per.PersonFirstName
PersonLastName = per.PersonLastName})
Is there a way to populate Persons.addressDescription without assigning individually the other properties of Persons? Imagine if Persons have 10 more properties.
I would like to refrain from using loops like:
foreach(Person person in PersonList)
{
foreach(Address address in AddressList)
{
if(person.addressId == address.addressId){
person.addressDescription = address.addressDescription
}
}
}
var query = persons.join(address,
per = person.addressId,
add = addressId
(per,add) =>
{
per.addressDescription = add.addressDescription;
return per;
});
var id = 1;
var query = database.Posts // your starting point - table in the "from" statement
.Join(database.Post_Metas, // the source table of the inner join
post => post.ID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
meta => meta.Post_ID, // Select the foreign key (the second part of the "on" clause)
(post, meta) => new { Post = post, Meta = meta }) // selection
.Where(postAndMeta => postAndMeta.Post.ID == id); // where statement

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"
}

Linq Select Clause w/ Unknown Number of Fields

I have a linq query in which I need to be able to select an variable number of fields from a datatable. I do know all of the fields that could be included, but only two will for sure be in the datatable. I also will know which fields are included in the datatable (it will just be different depending on the user's selections). Right now I set up something like this:
var query = from item in dt.AsEnumerable()
group item by item.Field<string>("ID") into g
select new
{
ID = g.Key, //required
Status = g.Min(i => dostuff(i,"Status")), //not required
Disc = g.Min(i => dostuff(i,"Disc")), //not required
Loc = String.Join<string>(",", from i in g select i.Field<string>("Loc")) //required
};
dostuff(DataRow i,string field)
{
try
{
return i.Field<string>(field);
}
catch
{
return null;
}
}
So dostuff basically is just checking whether or not that field exists in the dataset, and then I would just need to ignore the non-existant fields when working with the query results, which would not be too difficult. However, it seems like there is probably a better way to do this, but I've had a tough time finding anything via Google about using a dynamic select clause.
You could do it with dynamic type (nb, I did not test so this might have typos.):
var query =dt.AsEnumerable().GroupBy(item => item.Field<string>("ID"))
.Select(g => {
dynamic t = new System.Dynamic.ExpandoObject();
if (g.Table.Columns.Any(c => c.ColumnName == "Status"))
t.Status = g.Field<string>("Status");
if (g.Table.Columns.Any(c => c.ColumnName == "Disc"))
t.Disc = g.Field<string>("Disc");
t.ID = g.Key;
t.Loc = String.Join<string>(",",g.Select(i => i.Field<string>("Loc")));
return t;
}

Categories