Linq query to select all records that have sub records that match all values in an array of values? - linq

I have a table that contains records that have a related table that may have multiple records for each of the main records. This is a table of flags.
i.e.
MyRecord can have multiple subrecords Flag1, Flag4, Flag7
I am trying to create a Linq query that will return records that have all the flags I specify.
This is code of what I am trying to do
var flags = new List<string>() { "Flag1"};
db.Contents.Include(f=>f.Flags)
.Where(a => flags.All(b=>a.Flags.Any(f =>f.Name==b)));
The above almost works but returns records with Flag1 along with records that have Flag1,Flag4 and Flag1,Flag4,Flag7. I need to return only records that have the requested flags set.

var answer = db.Contents.Include(x => x.Flags)
.Where(x =>
x.Flags.Select(y => y.Name).Distinct().Count() == flags.Count
&&
flags.All(y => x.Flags.Any(z => z.Name == y)))
.ToList();

Related

finding multiple row indexes from a datagridview with linq

the below answer gets me the first row index but there are cases where there are multiple rows with my where clause. how do i get a "record set" where there multiple rows.
int index = -1;
DataGridViewRow rowx =
dgvMatchErrors.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells[1].Value.ToString().Equals(intErrorRowid.ToString()))
.First();
index = rowx.Index;
How to find the row ID from datagridview, given a row value?
You can try by removing First() method call in query
DataGridViewRow rowx =
dgvMatchErrors.Rows.Cast<DataGridViewRow>()
.Where(r => r.Cells[1].Value.ToString().Equals(intErrorRowid.ToString())).Select(r=>r);
This gives me a list of all my row index based on my where clause.
List<DataGridViewRow> rows =
dgvMatchErrors.Rows.Cast<DataGridViewRow>().Where(
r => r.Cells[1].Value.ToString().Equals(intErrorRowid.ToString())
).ToList();

Get distinct value from database

I want to get the distinct list of studentname from the database who are still active. Ihis is what I've tried.
string strJSON = JsonConvert.SerializeObject(
context.Students.Where(x => x.IsActive == 1).Distinct().ToList());
Distinct function works on all columns, so I assume that you want only student name.
string strJSON = JsonConvert.SerializeObject(
context
.Students
.Where(x => x.IsActive==1)
.Select(x=>x.StudentName)
.Distinct()
.ToList()
);

NotSupportedException for LINQ Queries

I am trying to get a list of a database table called oracleTimeCards whose employee id equals to the employeeID in employees list. Here is what I wrote:
LandornetSQLEntities db = new LandornetSQLEntities();
List<OracleEmployee> employees = db.OracleEmployees.Where(e => e.Office.Contains(officeName) && e.IsActive == true).Distinct().ToList();
var oracleTimeCards = db.OracleTimecards.Where(c => employees.Any(e => c.PersonID == e.PersonID)).ToList();
Anyone has any idea?
I'm going to assume you're using Entity Framework here. You can't embed calls to arbitrary LINQ extension methods inside your predicate, since EF might not know how to translate these to SQL.
Assuming you want to find all the timecards for the employees you found in your first query, you have two options. The simplest is to have a navigation property on your Employee class, named let's say TimeCards, that points to a collection of time card records for the given employee. Here's how that would work:
var oracleTimeCards = employees
.SelectMany(e => e.TimeCards)
.ToList();
If you don't want to do this for whatever reason, you can create an array of employee IDs by evaluating your first query, and use this to filter the second:
var empIDs = employees
.Select(e => e.PersonID)
.ToArray();
var oracleTimeCards = db.OracleTimecards
.Where(tc => empIDs.Contains(tc.PersonID))
.ToList();

JoinQueryOver in QueryOver to select notin list

I have a list of record that I picked up through the code:
var list= NhSession.QueryOver<Data.Models.MembModel>()
.Where(w => w.Comp.Id == idcomp)
.JoinQueryOver(jq => jq.Ver)
.Select(s => s.Ver)
.List<Dados.Models.VerModel>();
With this code I get a list of VerModel that I have relation in a MembModel. The problem is that I what get the list of VerModel that don't be in relation in a MembModal, I think to describe this, I want to select one list that is "notin" a first list. How can I do this?
Tks
What we need, as you said, is a NOT IN (subquery) statement. And NHibernate does have a clear way how to achieve that. First the subquery, which will return MembModel collection (filtered or not - as needed), represented by the VerModel.ID
var subquery = QueryOver.Of<Data.Models.MembModel>()
// we can still filter this sub-select ... or not
// .Where(w => w.Comp.Id == idcomp)
// what we need to be returned is the reference id, the VerModel.ID
.Select(m => m.Ver.ID);
And now we will query the VerModel itself, with the NOT IN (subquery) clause:
var list = session.QueryOver<Dados.Models.VerModel>()
.WithSubquery
.WhereProperty(v => v.ID) // the ID to match the prev selected one
.NotIn(subquery) // should NOT be IN
.List<Dados.Models.VerModel>();
Check:
16.8. Subqueries

Groupby and where clause in Linq

I am a newbie to Linq. I am trying to write a linq query to get a min value from a set of records. I need to use groupby, where , select and min function in the same query but i am having issues when using group by clause. here is the query I wrote
var data =newTrips.groupby (x => x.TripPath.TripPathLink.Link.Road.Name)
.Where(x => x.TripPath.PathNumber == pathnum)
.Select(x => x.TripPath.TripPathLink.Link.Speed).Min();
I am not able to use group by and where together it keeps giving error .
My query should
Select all the values.
filter it through the where clause (pathnum).
Groupby the road Name
finally get the min value.
can some one tell me what i am doing wrong and how to achieve the desired result.
Thanks,
Pawan
It's a little tricky not knowing the relationships between the data, but I think (without trying it) that this should give you want you want -- the minimum speed per road by name. Note that it will result in a collection of anonymous objects with Name and Speed properties.
var data = newTrips.Where(x => x.TripPath.PathNumber == pathnum)
.Select(x => x.TripPath.TripPathLink.Link)
.GroupBy(x => x.Road.Name)
.Select(g => new { Name = g.Key, Speed = g.Min(l => l.Speed) } );
Since I think you want the Trip which has the minimum speed, rather than the speed, and I'm assuming a different data structure, I'll add to tvanfosson's answer:
var pathnum = 1;
var trips = from trip in newTrips
where trip.TripPath.PathNumber == pathnum
group trip by trip.TripPath.TripPathLink.Link.Road.Name into g
let minSpeed = g.Min(t => t.TripPath.TripPathLink.Link.Speed)
select new {
Name = g.Key,
Trip = g.Single(t => t.TripPath.TripPathLink.Link.Speed == minSpeed) };
foreach (var t in trips)
{
Console.WriteLine("Name = {0}, TripId = {1}", t.Name, t.Trip.TripId);
}

Resources