How to use sql IN statement in linq lambda with 2 statements - c#

My statement is
Contents.
Select(x=> new
{
ContentUsers = x.ContentUsers.
Where(t=>t.UserId==2).
Select(t=>t.ContentId)
}).
Where(y=>y.ContentUsers.Any())
It gives me some Ids that i want to use it my another statements.
Contents.Where(x=>x.Id == 633,634,635)
How can i merge them?

What you're missing is the Contains function. It will probably be simpler to express this in a single query expression. If I translate your code to a single query expression, I looks a something like this:
var content =
from c in Contents
let contentUsers =
from x in Contents
select new
{
ContentUsers =
from t in x.ContentUsers
where t.UserId == 2
select t.ContentId
}
where contentUsers.Any(cu => cu.ContentUsers.Contains(c.Id))
select c;
However, it looks like all you want is to get just the Content records associated with a given UserID in the ContentUsers collection. This is a lot easier.
var content =
from c in Contents
where c.ContentUsers.Any(t => t.UserId == 2)
select c;
or if you prefer
var content = Contents.Where(c => c.ContentUsers.Any(t => t.UserId == 2));

Related

how to combine two linq query into one in c#

var patientList = uow.patientRepo.Get(p=>p.NutrititnistId == nutritionistId).select(y=>y.Id).toList();
var logList = uow.changeLogRepo.Get(c=>(c.EntityType.Equals("Program")) ||(patientList.any(s=>s==c.PatientId)));
Instead of retrieving that patientList, I want to combine that two linq statements into one statement
what can I do..?
Assuming you have an association between ChangeLog and Patient, you should be able to do this...
var logList = uow.changeLogRepo.Get(c=>(c.EntityType.Equals("Program")) ||
(c => c.Patients.any(p => p.NutrititnistId == nutritionistId)));

What is lambda equivalent an SQL "in" statement?

I can't figure out a lambda equivalent of this sql statement:
select * from Document
where Document.OrginalDocumentNumber
in (select documentAccess.DocumentId from documentAccess where userId='1')
The problem is that Document & documentaccess tables have no relation to each other.
Any help would be so much appreciated.
Replace IN with EXISTS and you get following:
from d in dbContext.Documents
where dbContext.documentAccesses.Any(
x=>x.DocumentId == d.OrginalDocumentNumber && x.userId == '1' )
select d
Normally, if you have sensible navigation properties, you can avoid join or sub-queries directly:
var documents = from documentAccess in contex.DocumentAccesses
where documentAccess.UserId == 1
select documentAccess.Document;
You may want to use .Distinct() on the results, depending on your data.
Similarly:
var documents = contex.DocumentAccesses
.Where(access => access.UserId == 1)
.Select(access => access.Document);
And even better, if you already have a User in context:
var documents = currentUser.DocumentAccesses.Select(access => access.Document);

Building a custom|progressive query in LINQ?

I have a page with five text boxes, each one representing a field in my database table and a search button:
If I were using SQL I could build my SQL statement depending on which fields have data in them.
However, I want to use LINQ, and I'm at a loss as to how to accomplish this. For instance, take a look at the query below:
var db = new BookDBDataContext();
var q =
from a in db.Books
where a.Title.Contains(txtBookTitle) &&
a.Author.Contains(txtAuthor) &&
a.Publisher.Contains(txtPublisher)
select a.ID;
The query above will return data where all the fields match data in the table. But, what if the user didn't enter an Author in the txtAuthor field? If I were building this as a query string, I could check each field for data and add it to the query string. Since this is LINQ, I can't dynamically change the search criteria, it seems.
Any advice would be greatly appreciated!
var db = new BookDBDataContext();
var q = (from a in db.Books
where a.Title.Contains(txtBookTitle));
if(!String.IsNullOrEmpty(txtAuthor))
{
q = q.Where(a => a.Author.Contains(txtAuthor));
}
if(!String.IsNullOrEmpty(txtAuthor))
{
q = q.Where(a => a.Publisher.Contains(txtPublisher));
}
var id = q.Select(a => a.ID);
from a in db.Books
where (string.isNullorWhiteSpace(search) || a.Title.Contains(search)) &&
(string.isNullorWhiteSpace(txtAuthor) || a.Author.Contains(txtAuthor) ) &&
(string.isNullorWhiteSpace(txtPublisher) || a.Publisher.Contains(txtPublisher))
select a.ID;

C# Linq Select Rows Where ID Equals ID in CSV

What I have is a string of comma separated IDs that I'm receiving from a query string (e.g. 23,51,6,87,29). Alternately, that string could just say "all".
In my Linq query I need a way to say (in pseudo code):
from l in List<>
where l.Id = all_of_the_ids_in_csv
&& other conditions
select new {...}
I'm just not sure how to go about doing that. I'm not even sure what to google to get me going in the right direction. Any pointing in the right direction would be extremely helpful.
I would suggest to split your query in 2 - first part will select by ID, and the select one will select other conditions.
First of all: check if query string contains numbers, or is just all:
var IEnumerable<ListItemType> query = sourceList;
if(queryStringValue != "All")
{
var ids = queryStringValue.Split(new[] { ',' })
.Select(x => int.Parse(x)) // remove that line id item.Id is a string
.ToArray();
query = query.Where(item => ids.Contains(item.Id));
}
from l in query
// other conditions
select new {...}
Because LINQ queries have deffered execution you can build queries like that without performance drawback. Query won't be executed until you ask for results (by ToList call or enumeration).
If you really want it with just one LINQ query:
var idArray = all_of_the_ids_in_csv.Split(',');
from l in List<>
where (all_of_the_ids_in_csv == "All" || idArray.Contains(l.Id))
&& other conditions
select new {...}
The trick is using string.Split
var ids = string.split(rawIdString, ",").ToList();
var objects = ids.Where(id=> /*filter id here */).Select(id=>new { /* id will be the single id from the csv */ });
// at this point objects will be an IEnumerable<T> where T is whatever type you created in the new statement above

filter a linq query based on the results of another query's results

I am wanting to filter a linq query
I have 2 linq statements
The 1st gets all the stores I want and the 2nd is where I filter information based on the results found in the 1st query.
var stores = ctx.Stores.Where(ps => ps.ParentStoreID == parent.ParentStoreID && ps.StoreID!=storeID);
var query = (from a in ctx.TransactionTable
from b in ctx.MappingTable.Where(x => x.TransactionId== a.TransactionId).DefaultIfEmpty()
where a.StoreID!=storeID
select new
{
Transactions = a,
Mapping = b
}).ToList();
How do I add another where clause into my 2nd query to only return results where a.StoreId is contained within the stores result?
Like this:
var stores = ctx.Stores.Where(ps => ps.ParentStoreID == parent.ParentStoreID && ps.StoreID!=storeID);
var query = (from a in ctx.TransactionTable
from b in ctx.MappingTable.Where(x => x.TransactionId==a.TransactionId).DefaultIfEmpty()
where a.StoreID!=storeID && stores.Select(s => s.StoreID).Contains(a.StoreID)
select new
{
Transactions = a,
Mapping = b
}).ToList();
You can find more info here:
Linq to Entities - SQL "IN" clause

Categories

Resources