Linq Merge Queries - c#

I have two queries that I would like to merge. This might be a left outer join, but it seems different.
The first query selects distinct stuff from a table:
var d = from d in db.Data
select (d.ID, d.Label, Value = 0).Distinct;
Lets suppose this returns the following:
{1,"Apple",0}
{2,"Banana",0}
{3,"Cabbage",0}
I then have another query that makes a different selection:
var s = from d in db.Data
where d.Label != "Apple"
select (d.ID, d.Label, d.Value);
This returns:
{2,"Banana",34}
{3,"Cabbage",17}
I then want a third query that joins the d and s together based upon their ID and their Label. I want the result to look like this:
{1,"Apple",0}
{2,"Banana",34}
{3,"Cabbage",17}
I'm basically just updating the numbers in the third query, but I have no idea how I should be doing this. It feels like it should be a simple join, but I just cannot get it to work.

This should work:
var query1 = from d in db.Data
select new { d.ID, d.Label, Value = 0 }.Distinct();
var query2 = from d in db.Data
where d.Label != "Apple"
select new { d.ID, d.Label, d.Value };
var result =
from d1 in query1
join d2 in query2 on new { d1.ID, d1.Label } equals new { d2.ID, d2.Label } into j
from d2 in j.DefaultIfEmpty()
select new
{
d1.ID,
d1.Label,
Value = d2 != null ? d2.Value : d1.Value
};
Note: are you sure you want to join on the ID and the label ? It seems rather strange to me... the label shouldn't be part of the key, so it should always be the same for a given ID

Here is one using method chain, which is my personal favorite.
var one = db.Data.Select(f => new {f.Id, f.Label, Value = 0});
var two = db.Data.Select(f => f).Where(f => f.Label != "Apple");
var three = one.Join(two, c => c.Id, p => p.Id, (c, p) => new {c.Id, c.Label, p.Value});

Could you just do
var s = from d in db.Data
select new
{
Id = d.ID,
Label = d.Label,
Value = (d.Label == "Apple" ? 0 : d.Value)
};

Related

linq expression (entity) with sum in subselect

I am new to Entity, and have a question regarding a LINQ statement.
Below appears my code, it appears with exception to "TotalFoults" field. He always gives 0.
Could anyone help me because all the results in the "TotalFoults" column have a value above zero.
Thank you very much.
var result = (from sr in db.StudentsResult
join F in db.Fouls on sr.Enrollment equals F.Enrollment into F_join
from F in F_join.DefaultIfEmpty()
join S in db.Students on sr.Enrollment equals S.Enrollment into A_join
from A in A_join.DefaultIfEmpty()
where
F.Day != null
group new { sr, s } by new
{
sr.Enrollment ,
sr.Name,
sr.Number,
sr.Classes,
s.Discount
} into g
orderby
g.Key.Classes,
g.Key.Number,
g.Key.Name
select new frequencyMod()
{
Enrollment = g.Key.Enrollment ,
StudentName = g.Key.Name,
StudentFile= g.Key.Number,
Classes = g.Key.Classes,
TotalFoults = (from m0 in db.Foults
where
m0.Enrollment == g.Key.Enrollment
group m0 by new
{
m0.Enrollment
} into a
select new
{
Total = a.Sum(p => p.Foults)
}).FirstOrDefault().Total
}).ToList();

Not counting null values from a linq LEFT OUTER JOIN query

I have this sql query that does exactly what i want but i need it in linq. It returns a few AVC rows and counts how many PersonAVCPermission that has status 1 linked to it
SELECT a.Id, a.Name, a.Address, COUNT(p.AVCID) AS Count
FROM AVC AS a
LEFT OUTER JOIN
(
SELECT PersonAVCPermission.AVCId
FROM PersonAVCPermission
WHERE PersonAVCPermission.Status = 1
) AS p
ON a.Id = p.AVCId
GROUP BY a.Id, a.Name, a.Address
I have this query in linq and it does the same thing except when there are no PersonAVCPermission it still counts 1
var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);
var q = from a in odc.AVCs
from p in yellows.Where(o => o.AVCId == a.Id).DefaultIfEmpty()
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
Id = agroup.Key.Id,
Name = agroup.Key.Name,
Address = agroup.Key.Address,
Count = agroup.Count(o => o.Id != null)
};
Im guessing that with DefaultIfEmpty() it places null rows in the list that then gets counted so i try to exclude them with (o => o.Id != null) but it still counts everything as at least one
If i dont use DefaultIfEmpty() it skips the rows with count 0 completely
How can i exclude them or am i doing it completely wrong?
How about using .Any() and a Let?
var yellows = odc.PersonAVCPermissions.Where(o => o.Status == (int)AVCStatus.Yellow);
var q = from a in odc.AVCs
let Y = (from p in yellows.Where(o => o.AVCId == a.Id) select p).Any()
where Y == true
group a by new { a.Id, a.Name, a.Address } into agroup
select new AVCListItem
{
Id = agroup.Key.Id,
Name = agroup.Key.Name,
Address = agroup.Key.Address,
Count = agroup.Count(o => o.Id != null)
};
You don't need the join, nor the grouping:
var q = from a in odc.AVCs
select new AVCListItem
{
Id = a.Id,
Name = a.Name,
Address = a.Address,
Count = yellows.Where(o => o.AVCId == a.Id).Count()
};

linq after groupby unable to get column values

I am getting data from multiple tables by joining and i want to group data on particular column value but after group by statement i can access my aliases and their properties. What mistake i am making?
public List<PatientHistory> GetPatientHistory(long prid)
{
using(var db = new bc_limsEntities())
{
List<PatientHistory> result =
(from r in db.dc_tresult
join t in db.dc_tp_test on r.testid equals t.TestId into x
from t in x.DefaultIfEmpty()
join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
from a in y.DefaultIfEmpty()
where r.prid == prid
group new {r,t,a} by new {r.testid} into g
select new PatientHistory
{
resultid = r.resultid,
bookingid = r.bookingid,
testid = r.testid,
prid = r.prid,
attributeid = r.attributeid,
result = r.result,
Test_Name = t.Test_Name,
Attribute_Name = a.Attribute_Name,
enteredon = r.enteredon,
Attribute_Type = a.Attribute_Type
}).ToList();
return result;
}
}
You're doing this wrong way. As been said by Jon after grouping the sequences with aliases r,t,a doesn't exist. After grouping you receive the sequence g with sequances of r,t,a in each element of g. If you want get one object from each group (for example most recent) you should try this:
List<PatientHistory> result =
(from r in db.dc_tresult
join t in db.dc_tp_test on r.testid equals t.TestId into x
from t in x.DefaultIfEmpty()
join a in db.dc_tp_attributes on r.attributeid equals a.AttributeId into y
from a in y.DefaultIfEmpty()
where r.prid == prid
group new {r,t,a} by new {r.testid} into g
select new PatientHistory
{
resultid = g.Select(x => x.r.resultid).Last(), // if you expect single value get it with Single()
// .... here add the rest properties
Attribute_Type = g.Select(x => x.a.Attribute_Type).Last()
}).ToList();
I appreciated this question so I thought I would add another potential usage case. I would like feedback on what the cleanest approach is to getting table information through a group operation so that I can project later in the select operation. I ended up combining what the OP did which is to pass objects into his group clause and then used the g.Select approach suggested by YD1m to get table information out later. I have a LEFT JOIN so I'm defending against nulls :
// SQL Query
//DECLARE #idCamp as Integer = 1
//
//select *,
//(select
//count(idActivityMaster)
//FROM tbActivityMasters
//WHERE dftidActivityCategory = A.idActivityCategory) as masterCount
//FROM tbactivitycategories A
//WHERE idcamp = #idCamp
//ORDER BY CategoryName
int idCamp = 1;
var desiredResult =
(from c in tbActivityCategories
.Where(w => w.idCamp == idCamp)
from m in tbActivityMasters
.Where(m => m.dftidActivityCategory == c.idActivityCategory)
.DefaultIfEmpty() // LEFT OUTER JOIN
where c.idCamp == idCamp
group new {c, m} by new { m.dftidActivityCategory } into g
select new
{
idActivityCategory = g.Select(x => x.m == null ? 0 : x.m.dftidActivityCategory).First(),
idCamp = g.Select(x => x.c.idCamp).First(),
CategoryName = g.Select(x => x.c.CategoryName).First(),
CategoryDescription = g.Select(x => x.c.CategoryDescription).First(),
masterCount = g.Count(x => x.m != null)
}).OrderBy(o=> o.idActivityCategory);
desiredResult.Dump("desiredResult");
If I just use a basic group approach I get the results but not the extra column information. At least I can't find it once I group.
var simpleGroup = (from c in tbActivityCategories
.Where(w => w.idCamp == idCamp)
.OrderBy(o => o.CategoryName)
from m in tbActivityMasters
.Where(m => m.dftidActivityCategory == c.idActivityCategory)
.DefaultIfEmpty() // LEFT OUTER JOIN
where c.idCamp == idCamp
group m by m == null ? 0 : m.dftidActivityCategory into g
select new
{
// How do I best get the extra desired column information from other tables that I had before grouping
// but still have the benefit of the grouping?
// idActivityCategory = g.Select(x => x.m == null ? 0 : x.m.dftidActivityCategory).First(),
// idCamp = g.Select(x => x.c.idCamp).First(),
// CategoryName = g.Select(x => x.c.CategoryName).First(),
// CategoryDescription = g.Select(x => x.c.CategoryDescription).First(),
// masterCount = g.Count(x => x.m != null)
idActivityCategory = g.Key,
masterCount = g.Count(x => x != null)
});
simpleGroup.Dump("simpleGroup");
Please tear this up. I'm trying to learn and it just seems like I'm missing the big picture here. Thanks.
UPDATE : Cleaned up by moving the work into the group and making the select more straight forward. If I had known this yesterday then this would have been my original answer to the OP question.
int idCamp = 1;
var desiredResult =
(from c in tbActivityCategories
.Where(w => w.idCamp == idCamp)
from m in tbActivityMasters
.Where(m => m.dftidActivityCategory == c.idActivityCategory)
.DefaultIfEmpty() // LEFT OUTER JOIN
where c.idCamp == idCamp
group new { c, m } by new
{ idActivityCategory = m == null ? 0 : m.dftidActivityCategory,
idCamp = c.idCamp,
CateGoryName = c.CategoryName,
CategoryDescription = c.CategoryDescription
} into g
select new
{
idActivityCategory = g.Key.idActivityCategory,
idCamp = g.Key.idCamp,
CategoryName = g.Key.CateGoryName,
CategoryDescription = g.Key.CategoryDescription,
masterCount = g.Count(x => x.m != null)
}).OrderBy(o => o.idActivityCategory);
desiredResult.Dump("desiredResult");

LINQ Filter anonymous type based on IEnumerable values within type

I'm using LINQ to SQL like:
var b =
from s in context.data
select new
{
id = s.id,
name = s.name
myEnumerable = s.OneToMany
};
Where myEnumerable is of type IEnumberable<T> and I want to now get a subset of b based upon properties of the individual items of myEnumerable. For example, say <T> has properties Berry and BerryID, I would want to do something like:
b =
from p in b
where //p.myEnumerable.myType.BerryID== 13
select p;
I'm feel like I'm missing something easy...
Since myEnumerable is an IEnumerable you will have to do a where on that.
var filteredData = from p in listOfData
where p.InnerData.Where(b=>b.ID == 13).Count() > 0
select p;
If I understand what you are saying...this is if there is an ID = 13 in the Enumerable at all.
Are you looking to select p if any of the items in p.myEnumerable have BerryID equal to 13?
b = from p in b
where p.myEnumerable.Any(t => t.BerryID == 13)
select p;
Or are you looking to select p if all of the items in p.myEnumerable have BerryID equal to 13?
b = from p in b
where p.myEnumerable.All(t => t.BerryID == 13)
select p;
What exactly is the condition you want the items in p.myEnumerable to fulfill before you select p?
Keep only items with at least one item having BerryID equal to 13 in the collection.
var b = context.data
.Where(s => s.OneToMany.Any(i => i.BerryID == 13))
.Select(s => new { id = s.id, name = s.name, myEnumerable = s.OneToMany });
Keep only items with all item having BerryID equal to 13 in the collection.
var b = context.data
.Where(s => s.OneToMany.All(i => i.BerryID == 13))
.Select(s => new { id = s.id, name = s.name, myEnumerable = s.OneToMany });

Linq query with left join and group

I'm unable to convert this SQL query into a working linq statement
select sum(cena), id_auta, max(servis)
from dt_poruchy left outer join mt_auta on dt_poruchy.id_auta=mt_auta.id
where dt_poruchy.servis>=3 group by id_auta;
I tryed something like this but i cant handle the select statement
var auta = from a in MtAuta.FindAll()
join p in DtPoruchy.FindAll() on a equals p.MtAuta into ap
from ap2 in ap.DefaultIfEmpty()
where ap2.SERVIS >= 3
group ap2 by ap2.ID into grouped
select new {
I'll appreciate any help!
Based on the limited information provided (which tables are certain fields from?), here is what I came up with.
var auta = from a in MtAuta.FindAll()
let p = a.DtPoruchys.Where(s => s.SERVIS >= 3)
select new
{
Id = a.Id,
CenaSum = p.Sum(c => c.Cena),
Servis = p.Max(s => s.SERVIS)
};
I've reached this solution (supposing "cena" belongs to MtAuta.FindAll()):
var auta = from e in
(from a in DtPoruchy.FindAll()
where a.SERVIS >= 3
join p in MtAuta.FindAll() on a.MtAuta equals p.Id into ap
from ap2 in ap.DefaultIfEmpty()
select new
{
Cena = ap.cena,
IdAuta = a.MtAuta,
Servis = a.servis
})
group e by e.IdAuta into g
select new
{
Cena = g.Sum(e => e.cena),
IdAuta = g.Key,
Servis = g.Max(e => e.servis)
};
I am not sure which table cena and servis are coming from but to create grouped sum you do something like.
select new { Sum = grouped.Sum( x => x.cena ) }
and to get max
select new { Max = grouped.Group.Max( x => x.servis ) }
Here is a good reference for you.
MSDN - 101 LINQ Samples
I've modified your solution little bit and i got it working like this:
var auta = from jo in
(
from a in MtAuta.FindAll()
join p in DtPoruchy.FindAll() on a equals p.MtAuta into ap
from ap2 in ap.DefaultIfEmpty()
where ap2.SERVIS >= 3
select new
{
Cena = ap2.CENA,
Idauto = ap2.ID_AUTA,
Servis = ap2.SERVIS
}
)
group jo by jo.Idauto into g
select new
{
Cena = g.Sum(jo => jo.Cena),
IdAuto = g.Key,
Servis = g.Max(jo => jo.Servis)
};
I just curious if this is the best solution?

Categories

Resources