I have 2 tables:
specs {specId, desc, createdby, lastupdatedby}
users {userid, username}
I want the below linq query need to be written in pure lambda expression
from spec in specs
from user in users.where(x => x.userId== spec.createdby).DefaultIfEmpty()
from updatedUser in users.where(x => x.userId== spec.lastupdatedbyby).DefaultIfEmpty()
select new {
spec = spec
user = user,
updatedUser = updatedUser
}
Please assist.
Data would be like say:
spec[{1, test, 1234, 2345},{2, test1, 1234, null}]
users[{1234, Allen},{2345, Dwayne}]
So the result should be
[{1, test, Allen, Dwayne}, {2, test1, Allen, null}]
Let's start with these classes:
class Specs {
public int specId { get; set; }
public string desc { get; set; }
public int createdby { get; set; }
public int lastupdatedby { get; set; }
}
class Users {
public int userId { get; set; }
public string username { get; set; }
}
class UpdatedUser {
public int userId {get; set;}
public string username { get; set; }
}
Now the Linq query, for convenience I have created some example data:
var specs = new Specs[]
{
new Specs{specId = 1, desc = "Spec1", createdby=1, lastupdatedby=1},
new Specs{specId = 2, desc = "Spec2", createdby=2, lastupdatedby=3},
new Specs{specId = 3, desc = "Spec3", createdby=3, lastupdatedby=1},
new Specs{specId = 4, desc = "Spec4", createdby=3, lastupdatedby=3},
};
var user = new Users[]
{
new Users{userId = 1, username = "User1"},
new Users{userId = 2, username = "User2"},
};
var updatedUser = new UpdatedUser[]
{
new UpdatedUser{userId = 1, username = "UpdatedUser1"},
new UpdatedUser{userId = 2, username = "UpdatedUser2"},
};
var result = specs
.GroupJoin(user,
s => s.createdby,
u => u.userId,
(s, u) => u.Select(x => new {spec = s, user = x})
.DefaultIfEmpty(new {spec = s, user = (Users)null}))
.SelectMany(g => g)
.GroupJoin(updatedUser,
firstJoin => firstJoin.spec.lastupdatedby,
uu => uu.userId,
(firstJoin, uu) =>
uu.Select(y => new {spec = firstJoin.spec, user = firstJoin.user, updatedUser = y})
.DefaultIfEmpty(new {spec = firstJoin.spec, user = firstJoin.user, updatedUser = (UpdatedUser) null}))
.SelectMany(g1 => g1)
.ToList();
The GroupJoin extension method help you obtain a tuple with all the elements of the starting table with a list of elements of the joined table.
Now if you enumerate the results:
result.ForEach(item => {
Console.WriteLine(item.spec.desc);
Console.WriteLine(item.user != null ? item.user.username : "NULL");
Console.WriteLine(item.updatedUser != null ? item.updatedUser.username : "NULL");
Console.WriteLine();
});
You obtain this:
Spec1
User1
UpdatedUser1
Spec2
User2
NULL
Spec3
NULL
UpdatedUser1
Spec4
NULL
NULL
You can try
var list = specs.Join(users,
s => s.lastupdatedby,
u => u.userid,
(s, u) => new { specs = s, users = u })
.Select(x => new {
specId = x.specs.specId,
desc = x.specs.desc,
createdby=x.specs.createdby,
username=x.users.username
}).ToString();
LEFT JOIN MULTIPLE TABLES
------------------------
create table Rama(rid int,name varchar(80),zip int);
create table Kris(kid int,rid int, Title varchar(80),zip int);
insert into Rama values(1,'Robert Rama' ,10001),
(2,'Roger Raju' ,10002),
(3,'Kevin Kali' ,10003),
(4,'Mark Mutu' ,10004)
insert into Kris values(0,0,'NP' ,10001),
(1,1,'VP' ,10001),
(2,2,'AVP',10002)
//Lambda expression
//Download https://www.linqpad.net/Download.aspx
//Create tables as given below and connect linqpad to your db
//select C# statement(s) on linqpad and run below
var v =
from r in Ramas
join k in Kris
on new { r.Rid, r.Zip } equals new { k.Rid, k.Zip }
into resultGroups
from k in resultGroups.DefaultIfEmpty()
select new { r.Rid, r.Name, k.Title };
v.Dump();
Related
I'm writing new api call for my android app, I want to retrieve data from dynamic table, I mean when user select "A" button from Andriod I want to retrieve data from "A" table and if "B" is click , retrieve data from "B" table. Someone help me to find the possible solution.
I want to replace with variable for "JBCTNRITEMs" from entities.JBCTNRITEMs (table-name)
var query = (from jbct in entities.JBCTNRITEMs
where jbid.Contains(jbct.jbid.ToString()) && boxid.Contains(jbct.TrackingNo.ToString())
select jbct).ToArray();
int id = 0;
if (query.Length > 0)
{
id = (query[0].id);
}
return id;
Here are the two different possibilities as an example
if (module.ToLower() == "module-a")
{
var imageinfo = (from jb in entities.TableA.AsEnumerable()
where scanID.Contains(jb.aid.ToString())
select jb).ToArray();
InsertGENIMAGE(userID, scanID, FilePath, imageinfo, "AIMAGE");
}
else if (module.ToLower() == "module-b")
{
var imageinfo = (from jb in entities.TableB.AsEnumerable()
where scanID.Contains(jb.bid.ToString())
select jb).ToArray();
InsertGENIMAGE(userID, scanID, FilePath, imageinfo, "BIMAGE");
}
Here, query stores what you are you trying to select. As long as you are trying to select same type or same anonymous type, it will work.
Here is a simple example:
class Test1
{
public int ID { get; set; }
public string Name { get; set; }
}
class Test2
{
public int ID { get; set; }
public string Name { get; set; }
}
var test1Lst = new List<Test1>
{
new Test1() { ID = 1, Name = "Jitendra" },
new Test1() { ID = 2, Name = "Jahnavi" }
};
var test2Lst = new List<Test2>
{
new Test2() { ID = 1, Name = "Aaditri" },
new Test2() { ID = 2, Name = "Pankaj" }
};
var test = false;
var query = test ? (from t in test1Lst select new { ID = t.ID, Name = t.Name }) : (from t in test2Lst select new { ID = t.ID, Name = t.Name });
// Put whatever condition you want to put here
query = query.Where(x => x.ID == 1);
foreach(var t1 in query)
{
Console.WriteLine(t1.ID + " " + t1.Name);
}
I guess in this case I would suggest to use a generic method :
private T GetMeTheFirstEntry<T>(Expression<Func<T, bool>> filter) where T : class
{
return entities.GetTable<T>().FirstOrDefault(filter);
}
The GetTable will allow you to interchange the tableA and tableB. You would call it the following way:
TableA tableA_entity = GetMeTheFirstEntry<TableA>(jb => scanID.Contains(jb.aid.ToString()));
TableB tableB_entity = GetMeTheFirstEntry<TableB>(jb => scanID.Contains(jb.bid.ToString()));
If the filtering was successfull, then the retrieved object will not be null and you can use it:
int a_id = tableA_entity.aid;
I have fourtables:
CL_ProductType
CL_InsuranceProduct
PR_Product
PR_ProductInsuranceProduct (aggregation table for PR_Product and CL_InsuranceProduct)
I need left join for PR_ProductInsuranceProduct and I've done it with SelectMany() selector.
The problem is that this query has groupBy method, and I need to extract the max(ID_ProductInsuranceProduct).
My question is: How to extract in .SelectMany() the highist value of ID_ProductInsuranceProduct?
SQL that works:
select p.ID_Product,p.Name, p.Code, p.InProduction, MAX(pip.ID_ProductInsuranceProduct)
from PR_Product p
join CL_ProductType pt ON p.ID_ProductType = pt.ID_ProductType
left join PR_ProductInsuranceProduct pip ON p.ID_Product = pip.ID_Product
join CL_InsuranceProduct ip ON pip.ID_InsuranceProduct = ip.ID_InsuranceProduct
GROUP BY p.ID_Product,p.Name, p.Code, p.InProduction
My code in C# and LINQ Lambda:
var query = DBContext.PR_Product
.Where(m => m.Active)
.Where(nameFilter)
.Where(activationDateFilter)
.Where(closureDateFilter)
.Where(productTypeFilter)
.Where(subgroupFilter)
.Where(inproductionFilter)
.Where(answerFilter)
.Where(insuranceProductFilter)
.Where(excludePidsFilter)
.Join(DBContext.CL_ProductType, p => p.ID_ProductType, pt => pt.ID_ProductType,
(p, pt) => new { p, pt = pt.Name })
.GroupJoin(DBContext.PR_ProductInsuranceProduct,
p => p.p.ID_Product,
pip => pip.ID_Product,
(p1, pip) => new { Products = p1, ProductInsuranceProduct = pip })
.SelectMany
(
x => x.ProductInsuranceProduct.DefaultIfEmpty(),
(x, y) => new
{
x.Products.p.ID_Product,
x.Products.p.Name,
x.Products.p.Code,
x.Products.p.ActivationDate,
x.Products.p.ClosureDate,
x.Products.pt,
x.Products.p.InProduction,
//Here I want to fill in to my custom property max for ID_ProductInsuranceProduct, MaxId is a custom property in a model
x.Products.p.MaxId = x.ProductInsuranceProduct.Max(pip => pip.ID_ProductInsuranceProduct)
})
.GroupBy(x =>
new
{
x.ID_Product,
x.Name,
x.Code,
x.ActivationDate,
x.ClosureDate,
x.pt,
x.InProduction,
});
I assume, beacause it's a SelectMany, that my code returns "flatten" data into one single table, therefore, my method Max, its input is bad, because its not a collection?
Can I do left join in linq with just .Select()?
My continuation of the code, when I execute the query:
count = query.Count();
var list = query
.OrderBy(x => x.FirstOrDefault().Code)
.DoPaging(pageSize, pageIndex)
.ToList();
List<PR_Product> products =
(from m in list
select new PR_Product
{
ID_Product = m.Key.ID_Product,
Name = m.Key.Name,
Code = m.Key.Code,
ActivationDate = m.Key.ActivationDate,
ClosureDate = m.Key.ClosureDate,
ActivationDateString = m.Key.ActivationDate.ToString("d", new CultureInfo(DALParams.LCID, false)),
ClosureDateString = m.Key.ClosureDate.ToString("d", new CultureInfo(DALParams.LCID, false)),
ProductType = m.Key.pt,
InProduction = m.Key.InProduction
//MaxId = implemention...
}).ToList();
Given the following objects:
public class PR_Product
{
public int ID_Product { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public bool InProduction { get; set; }
}
public class PR_ProductInsuranceProduct
{
public int ID_ProductInsuranceProduct { get; set; }
public int ID_Product { get; set; }
}
I've create in memory collections to demonstrate how to extract max(property) from a left join in LINQ with a lambda expression:
var product = new List<PR_Product>
{
new PR_Product { ID_Product = 1, Name = "TestName1", Code = "TestCode1", InProduction = true },
new PR_Product { ID_Product = 2, Name = "TestName2", Code = "TestCode3", InProduction = true },
new PR_Product { ID_Product = 3, Name = "TestName3", Code = "TestCode3", InProduction = true }
};
var productInsurance = new List<PR_ProductInsuranceProduct>
{
new PR_ProductInsuranceProduct { ID_ProductInsuranceProduct = 111, ID_Product = 1 },
new PR_ProductInsuranceProduct { ID_ProductInsuranceProduct = 222, ID_Product = 1 },
new PR_ProductInsuranceProduct { ID_ProductInsuranceProduct = 333, ID_Product = 3 },
};
var result = product
.GroupJoin(productInsurance,
prProduct => prProduct.ID_Product,
insuranceProduct => insuranceProduct.ID_Product,
(prProduct, insuranceProduct) => new { prProduct, insuranceProduct })
.SelectMany(arg => arg.insuranceProduct.DefaultIfEmpty(), (prProduct, insuranceProducts) => new { prProduct })
.GroupBy(arg => new { arg.prProduct.prProduct.ID_Product, arg.prProduct.prProduct.Name, arg.prProduct.prProduct.Code, arg.prProduct.prProduct.InProduction})
.Select(grouping => new
{
grouping.Key.ID_Product,
grouping.Key.Name,
grouping.Key.Code,
Max_ID_ProductInsuranceProduct = grouping.FirstOrDefault()?.prProduct.insuranceProduct.DefaultIfEmpty().Max(insuranceProduct => insuranceProduct?.ID_ProductInsuranceProduct)
});
Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
Hope this helps.
Linq to SQL Concat / Union does not working on the Custom Class.
Custom Class
public class CustomClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Accesses> Accesses { get; set; }
}
Union:
IQueryable<CustomClass> objQuery = context.Users
.Where(W => W.Auth == true)
.Select(S => new CustomClass()
{
FirstName = S.FirstName,
LastName = S.LastName,
Accesses = context.AuthFalse
.Where(W => W.UID = S.ID)
.Select(S1 => new Accesses()
{
AccessesID = S1.AccessesID,
})
.ToList(),
})
.Union(context.Users
.Where(W => W.Auth == true)
.Select(S => new CustomClass()
{
FirstName = S.FirstName,
LastName = S.LastName,
Accesses = context.AuthTrue
.Where(W => W.UID = S.ID)
.Select(S1 => new Accesses()
{
AccessesID = S1.AccessesID,
})
.ToList(),
})
);
When I executing the above query I got the following error:
The 'Distinct' operation cannot be applied to the collection
ResultType of the specified argument.\r\nParameter name: argument
Concat
IQueryable<CustomClass> objQuery = context.Users
.Where(W => W.Auth == true)
.Select(S => new CustomClass()
{
FirstName = S.FirstName,
LastName = S.LastName,
Accesses = context.AuthFalse
.Where(W => W.UID = S.ID)
.Select(S1 => new Accesses()
{
AccessesID = S1.AccessesID,
})
.ToList(),
})
.Concat(context.Users
.Where(W => W.Auth == true)
.Select(S => new CustomClass()
{
FirstName = S.FirstName,
LastName = S.LastName,
Accesses = context.AuthTrue
.Where(W => W.UID = S.ID)
.Select(S1 => new Accesses()
{
AccessesID = S1.AccessesID,
})
.ToList(),
})
);
When I executing the above query I got the following error:
{"The nested query is not supported. Operation1='UnionAll'
Operation2='MultiStreamNest'"}
Finally, What I want to do is that if the Auth field of the Users table is true than I want the data from the AuthTrue table and want to store in the List field, If the Auth field of the Users table is false than I want the data from the AuthFalse table and want to store in the List field.
I want all this to do in the single query or maximum 2 to 3 query.
Thanks.
You should rewrite yours Concat attempt like this:
1. Start with users
2. Then do 2 left joins to AuthFalse and AuthTrue
3. Add filtering by user.Auth field and proper right match
4. Do select to anonymous class with user.Id, user.LastName, user.FirstName + either AuthFalse match or AuthTrue match. At this stage queriable must by casted ToEnumerable
5. Then all is left is proper grouping + selection.
Here is this steps as complete unit test:
public class CustomClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<CustomAccesses> Accesses { get; set; }
}
public class CustomAccesses
{
public int Rights { get; set; }
}
public class Accesses
{
public Guid ID { get; set; }
public Guid UID { get; set; }
public int Rights { get; set; }
}
public class User
{
public Guid ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool Auth { get; set; }
}
[TestFixture]
public class QueryTests
{
private static readonly User TrueUser = new User
{
ID = Guid.NewGuid(),
FirstName = "TrueFirstName",
LastName = "TrueLastName",
Auth = true
};
private static readonly User FalseUser = new User
{
ID = Guid.NewGuid(),
FirstName = "FalseFirstName",
LastName = "FalseLastName",
Auth = false
};
private static readonly User[] DbUsersMock =
{
TrueUser,
FalseUser
};
private static readonly Accesses[] DbAuthTrueMock =
{
new Accesses
{
ID = Guid.NewGuid(),
UID = TrueUser.ID,
Rights = 1
},
new Accesses
{
ID = Guid.NewGuid(),
UID = TrueUser.ID,
Rights = 2
}
};
private static readonly Accesses[] DbAuthFalseMock =
{
new Accesses
{
ID = Guid.NewGuid(),
UID = FalseUser.ID,
Rights = -1
},
new Accesses
{
ID = Guid.NewGuid(),
UID = FalseUser.ID,
Rights = -2
}
};
[Test]
public void Test()
{
var users = DbUsersMock.AsQueryable();
var authTrue = DbAuthTrueMock.AsQueryable();
var authFalse = DbAuthFalseMock.AsQueryable();
var result = users
.GroupJoin(
authTrue,
u => u.ID,
ta => ta.UID,
(user, accesses) => new
{
user,
accesses = accesses.DefaultIfEmpty()
}
)
.SelectMany(
ua => ua
.accesses
.Select(
trueAccess => new
{
ua.user,
trueAccess
}
)
)
.GroupJoin(
authFalse,
ua => ua.user.ID,
fa => fa.UID,
(userAccess, accesses) => new
{
userAccess,
accesses = accesses.DefaultIfEmpty()
}
)
.SelectMany(
uaa => uaa
.accesses
.Select(
falseAccess => new
{
uaa.userAccess.user,
uaa.userAccess.trueAccess,
falseAccess
}
)
)
.Where(
uaa => uaa.user.Auth
? uaa.trueAccess != null
: uaa.falseAccess != null
)
.Select(
uaa => new
{
uaa.user.ID,
uaa.user.FirstName,
uaa.user.LastName,
AccessID = uaa.user.Auth
? uaa.trueAccess.ID
: uaa.falseAccess.ID,
Rights = uaa.user.Auth
? uaa.trueAccess.Rights
: uaa.falseAccess.Rights
}
)
.OrderBy(uaa => uaa.ID)
.AsEnumerable()
.GroupBy(uaa => uaa.ID)
.Select(
g => new CustomClass
{
FirstName = g.First().FirstName,
LastName = g.First().LastName,
Accesses = g
.GroupBy(uaa => uaa.AccessID)
.Select(
uaa => new CustomAccesses
{
Rights = uaa.First().Rights
}
)
.ToList()
}
)
.ToArray();
Assert.That(result.Length, Is.EqualTo(DbUsersMock.Length));
}
}
You can do it in many ways. A simple way to do this is:
Take two lists, one for when it is TRUE and another for when it is FALSE. Then in the resulting list use the ADDRANGE method.
This method (ADDRANGE) will only work when you are working with lists.
Example:
var listTrue = ctx.Users.Where(...).Select(s=> new CustomClass{...}).ToList();
var listFalse = ctx.Users.Where(...).Select(s=> new CustomClass{...}).ToList();
var result = new List<CustomClass>();
result.AddRange(listTrue);
result.AddRange(listFalse);
return result;
I'm new in ASP, Entity and lambda expressions. How can I join two tables?
Route Model:
public partial class Route
{
public Route()
{
Flights = new HashSet<Flight>();
}
public int RouteID { get; set; }
public int DepartureAirportID { get; set; }
public int ArrivalAirportID { get; set; }
public int FlightDuration { get; set; }
public virtual Airport Airport { get; set; }
public virtual Airport Airport1 { get; set; }
public virtual ICollection<Flight> Flights { get; set; }
}
Airport Model:
public partial class Airport
{
public Airport()
{
Routes = new HashSet<Route>();
Routes1 = new HashSet<Route>();
}
public int AirportID { get; set; }
public string City { get; set; }
public string Code { get; set; }
public virtual ICollection<Route> Routes { get; set; }
public virtual ICollection<Route> Routes1 { get; set; }
}
SQL query looks like this:
SELECT a.AirportID, a.City
FROM Route r INNER JOIN Airport a ON r.ArrivalAirportID = a.AirportID
WHERE r.DepartureAirportID = #departureAirportID
ORDER BY a.City
Sorry for this easy question but I don't know how to do this with Entity Framework...
Something like this should do (untested and just going on from your query) with a variable hard-coded):
using (var db = new YourDbContext())
{
var query = from r in db.Route
join a in db.Airport a on r.ArrivalAirportID equals a.AirportID
where r.DepartureAirportID = 1 // replace with your varialble.
orderby a.City
select a;
}
Include with join entity framework. here doctorSendAnswerModel also a inner table.
var data = _patientaskquestionRepository.Table.Include(x=>x.DoctorSendAnswer).Join(_patientRepository.Table, a => a.PatientId, d => d.Id, (a, d) => new { d = d, a = a }).Where(x => x.a.DoctorId == doctorid);
if(!string.IsNullOrEmpty(status))
data=data.Where(x=>x.a.Status==status);
var result = data.Select(x => new {x= x.a,y=x.d }).ToList();
var dt = result.Select(x => new PatientAskQuestionModel()
{
PatientId = x.x.PatientId.Value,
AskQuestion = x.x.AskQuestion,
Id = x.x.Id,
DoctorId = x.x.DoctorId,
FileAttachment1Url = x.x.FileAttachment1,
DocName = x.y.FirstName + " " + x.y.LastName,
CreatedDate = x.x.CreatedDate.Value,
doctorSendAnswerModel = x.x.DoctorSendAnswer.Select(t => new DoctorSendAnswerModel { Answer = t.Answer }).ToList()
}).ToList();
return dt;
LinQ query:
from r in context.Route
join a in context.Airport
on r.ArrivalAirportID equals a.AirportID
WHERE r.DepartureAirportID = "value"
ORDER BY a.City
select a.AirportID, a.City
var balance = (from a in context.Airport
join c in context.Route on a.ArrivalAirportID equals c.AirportID
where c.DepartureAirportID == #departureAirportID
select a.AirportID)
.SingleOrDefault();
You can do the following:
var matches = from a in context.Airports
join r in context.Routes
on a.AirportID equals r.ArrivalAirportID
where r.DepartureAirportID = departureAirportID
order by a.City
select new
{
a.AirportID,
a.City
};
Entity query with conditional join with pagination.
if (pageIndex <= 0)
pageIndex = 1;
pageIndex = ((pageIndex - 1) * pageSize) ;
var patient = _patientRepository.Table.Join(_DoctorPatient.Table.Where(x => x.DoctorId == Id && x.IsBlocked==false), x => x.Id, d => d.PatientId, (x, d) => new { x = x });
if (state != "")
patient = patient.Where(x => x.x.State.Contains(state));
if (name != "")
patient = patient.Where(x => (x.x.FirstName + x.x.LastName).Contains(name));
if (sdate != null)
patient = patient.Where(x => x.x.CreatedDate >= sdate);
if (eDate != null)
patient = patient.Where(x => x.x.CreatedDate <= eDate);
var result = patient.Select(x => x.x).Select(x => new PatientDoctorVM() { PatientId = x.Id, Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, SSN = x.NewSSNNo, UserProfileId = x.UserProfileId, Email = x.Email, TumbImagePath = x.TumbImagePath }).OrderBy(x => x.Id).Skip(pageIndex).Take(pageSize).ToList();
Your entity and lembda query will be lool like this:
return (from d in _doctorRepository.Table
join p in _patientDoctor.Table on d.Id equals p.DoctorId
where p.PatientId == patientid.Value select d
).ToList();
Take a look at this site, it will explain you how the join works in Linq.
So if you ever need it again you will be able to solve it yourself.
My program is a task program of sorts. What I'd like to do is construct a UI for a user/employee to see tasks they have to do on the given day the log in.
I have two tables, PostOne and PostEig, in a 1-M.
PostOne is the master table that contains the information about a single task.
PostEig is a table of users that are assigned to a task in Post One.
The models [simplified]
public class PostOne
{
public string One { get; set; }
[Key]
public string Two { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime ThrD { get; set; }
}
public class PostEig
{
public string EigOne { get; set; }
public string EigTwo { get; set; } //foreign key
[Key]
public string EigID { get; set; }
[Required]
public string EigA { get; set; } //user login
}
I'm having trouble with the controller. I'm not even sure how to start on the code necessary to achieve my goal, so I'm going to try to write it out:
call a list of PostEigs Where EigA == User.Identity.Name
and from this list.. call a list of PostOnes Where Two == EigTwo
and from this list.. call a list of PostOnes Where ThrD == DateTime.UtcNow.Date
I did try something like this:
public ActionResult SkedList()
{
return View(db.PostEigs.Where(m =>
m.EigA == User.Identity.Name ||
m.EigTwo == db.PostOnes.Where(o => o.ThrD == DateTime.UtcNow.Date)
).ToList());
}
If this is unclear, please let me know. I appreciate any advice or solutions, even if in a different direction.
Sounds like this is a candidate for an Inner Join. I find it's much easier to think in terms of SQL then transform it into LINQ.
SQL Query:
SELECT
po.*
FROM
PostOnes po
INNER JOIN
PostEig pe
ON
pe.EigTwo = po.Two
WHERE
pe.EigA = AUTH_NAME AND po.ThrD = TODAY()
C# LINQ Query:
var DB_PostEig = new List<PostEig>()
{
new PostEig(){EigTwo = "Foo1", EigA = "Foo"},
new PostEig(){EigTwo = "Foo2", EigA = "Foo"},
new PostEig(){EigTwo = "Bar1", EigA = "Bar"},
new PostEig(){EigTwo = "Bar2", EigA = "Bar"}
};
var DB_PostOnes = new List<PostOne>()
{
new PostOne(){Two = "Foo1", ThrD = new DateTime(1900,1,1)},
new PostOne(){Two = "Foo2", ThrD = new DateTime(2000,1,1)},
new PostOne(){Two = "Foo3", ThrD = new DateTime(1900,1,1)},
new PostOne(){Two = "Bar1", ThrD = new DateTime(1900,1,1)},
new PostOne(){Two = "Bar2", ThrD = new DateTime(1900,1,1)}
};
var authName = "Foo";
var currentDate = new DateTime(1900,1,1);
//Not sure if this is the most optimal LINQ Query, but it seems to work.
var queryReturn = DB_PostOnes.Join(DB_PostEig.Where(x => x.EigA == authName), x => x.Two, y => y.EigTwo, (x, y) => x)
.Where(z => z.ThrD == currentDate)
.ToList();
queryReturn.ForEach(x => Console.WriteLine(x.Two + " - " + x.ThrD)); //Foo1 - 1/1/1900
Edit:
LINQ Query without a join
var queryTwo = DB_PostOnes
.Where(x => DB_PostEig.Any(y => y.EigTwo == x.Two && y.EigA == authName) && x.ThrD == currentDate)
.ToList();