Linq Lambda multiple tables ( 4 tables ) LEFT JOIN - linq

I have 4 tables;
TMain >> MainId (PK)
T1 >> T1_Id, MainId, X (PK and FK) X is decimal
T2 >> T2_Id, MainId, X (PK and FK) X is decimal
T3 >> T3_Id, MainId, X (PK and FK) X is decimal
Here SQL output;
SELECT TMain.*, (ISNULL(T1.X,0) + ISNULL(T2.X,0) + ISNULL(T3.X,0)) AS TOTAL FROM TMain
LEFT OUTER JOIN T1 ON TMain.MainId = T1.MainId
LEFT OUTER JOIN T2 ON TMain.MainId = T2.MainId
LEFT OUTER JOIN T3 ON TMain.MainId = T3.MainId
How can I write it LINQ LAMDA
var AbbA = MyContext.TMain
.GroupJoin(
MyContext.T1,
q1 => q1.TMainId,
q2 => q2.TMainId,
(x, y) => new { A = x, T1_A = y })
.SelectMany(
xy => xy.T1_A.DefaultIfEmpty(),
(x, y) => new { A = x.A, T1_A = y })
.GroupJoin(
MyContext.T2,
q1 => q1.A.TMainId,
q2 => q2.TMainId,
(x, y) => new { A = x, T2_A = y })
.SelectMany(
xy => xy.T2_A.DefaultIfEmpty(),
(x, y) => new { A = x.A, T2_A = y })
.GroupJoin(
MyContext.T3,
q1 => q1.A.A.TMainId,
q2 => q2.TMainId,
(x, y) => new { A = x, T3_A = y })
.SelectMany(
xy => xy.T3_A.DefaultIfEmpty(),
(x, y) => new { A = x.A, T3_A = y })
.Select(q => new
{
TMainId = q.A.A.A.TMainId,
Total = (q.T3_A.X == null ? 0 : q.T3_A.X) +
(q.A.T2_A.X == null ? 0 : q.A.T2_A.X) +
(q.A.A.T1_A.X == null ? 0 : q.A.A.T1_A.X),
}).ToList();
So I want to access T1 fields or TMain fields
I wrote q.A.A.T1_A.X or q.A.A.A. in linq select
Is that true? or have simplest way?

I cannot test now if will work, but sometimes you can write the GroupJoin like (if you expect 0 or N registers from T1):
.GroupJoin(MyContext.T1,
q1 => q1.TMainId,
q2 => q2.TMainId,
(x, y) => new { A = x, T1_A = y.DefaultIfEmpty() })
or (if you expect 0 or 1 registers from T1)
.GroupJoin(MyContext.T1,
q1 => q1.TMainId,
q2 => q2.TMainId,
(x, y) => new { A = x, T1_A = y.FirstOrDefault() })
It always depends what do you like to return for the next lambda, and in this case you don't need the SelectMany(). But this code will be the most simple left join you can get with linq/lambda if you cannot map accordingly the relationship between the tables.
You can simplify if you map the relationship between table TMain and T1 with "HasOptional", like:
modelBuilder.Entity<T1>()
.HasOptional(x => x.TMain)
.WithMany(y => y.T1s)
.HasForeignKey(x => x.TMaidId);
The "HasOptional()" shows to Entity Framework that this relationship are optional, so the LEFT JOIN will be used to mount the query. If you use "HasRequired()", will be used the JOIN.
So, you can use Include():
var AbbA = MyContext.TMain
.Include(x => x.T1s)
To left join T1 and T2:
var AbbA = MyContext.TMain
.Include(x => x.T1s.Select(y => y.T2s))

Related

Default values for empty groups in Linq GroupBy query

I have a data set of values that I want to summarise in groups. For each group, I want to create an array big enough to contain the values of the largest group. When a group contains less than this maximum number, I want to insert a default value of zero for the empty key values.
Dataset
Col1 Col2 Value
--------------------
A X 10
A Z 15
B X 9
B Y 12
B Z 6
Desired result
X, [10, 9]
Y, [0, 12]
Z, [15, 6]
Note that value "A" in Col1 in the dataset has no value for "Y" in Col2. Value "A" is first group in the outer series, therefore it is the first element that is missing.
The following query creates the result dataset, but does not insert the default zero values for the Y group.
result = data.GroupBy(item => item.Col2)
.Select(group => new
{
name = group.Key,
data = group.Select(item => item.Value)
.ToArray()
})
Actual result
X, [10, 9]
Y, [12]
Z, [15, 6]
What do I need to do to insert a zero as the missing group value?
Here is how I understand it.
Let say we have this
class Data
{
public string Col1, Col2;
public decimal Value;
}
Data[] source =
{
new Data { Col1="A", Col2 = "X", Value = 10 },
new Data { Col1="A", Col2 = "Z", Value = 15 },
new Data { Col1="B", Col2 = "X", Value = 9 },
new Data { Col1="B", Col2 = "Y", Value = 12 },
new Data { Col1="B", Col2 = "Z", Value = 6 },
};
First we need to determine the "fixed" part
var columns = source.Select(e => e.Col1).Distinct().OrderBy(c => c).ToList();
Then we can process with the normal grouping, but inside the group we will left join the columns with group elements which will allow us to achieve the desired behavior
var result = source.GroupBy(e => e.Col2, (key, elements) => new
{
Key = key,
Elements = (from c in columns
join e in elements on c equals e.Col1 into g
from e in g.DefaultIfEmpty()
select e != null ? e.Value : 0).ToList()
})
.OrderBy(e => e.Key)
.ToList();
It won't be pretty, but you can do something like this:
var groups = data.GroupBy(d => d.Col2, d => d.Value)
.Select(g => new { g, count = g.Count() })
.ToList();
int maxG = groups.Max(p => p.count);
var paddedGroups = groups.Select(p => new {
name = p.g.Key,
data = p.g.Concat(Enumerable.Repeat(0, maxG - p.count)).ToArray() });
You can do it like this:-
int maxCount = 0;
var result = data.GroupBy(x => x.Col2)
.OrderByDescending(x => x.Count())
.Select(x =>
{
if (maxCount == 0)
maxCount = x.Count();
var Value = x.Select(z => z.Value);
return new
{
name = x.Key,
data = maxCount == x.Count() ? Value.ToArray() :
Value.Concat(new int[maxCount - Value.Count()]).ToArray()
};
});
Code Explanation:-
Since you need to append default zeros in case when you have less items in any group, I am storing the maxCount (which any group can produce in a variable maxCount) for this I am ordering the items in descending order. Next I am storing the maximum count which the item can producr in maxCount variable. While projecting I am simply checking if number of items in the group is not equal to maxCount then create an integer array of size (maxCount - x.Count) i.e. maximum count minus number of items in current group and appending it to the array.
Working Fiddle.

How to calculate multiple averages in one query in linq to entities

How to do this in linq to entities in one query?
SELECT avg(Column1), avg(Column2), ... from MyTable
where ColumnX = 234
??
You could do something like that:
var averages = myTable
.Where(item => item.ColumnX == 234)
.Aggregate(
new { count = 0, sum1 = 0.0, sum2 = 0.0 },
(acc, item) => new { count = acc.count + 1, sum1 = acc.sum1 + item.Column1, sum2 = acc.sum2 + item.Column2 },
acc => new { avg1 = acc.sum1 / acc.count, avg2 = acc.sum2 / acc.count });
Note the call to AsEnumerable() to force Aggregate to be executed locally (as EF probably doesn't know how to convert it to SQL) Actually it seems to work ;)
Alternatively, you could use this query:
var averages =
from item in table
where item.ColumnX == 234
group item by 1 into g
select new
{
Average1 = g.Average(i => i.Column1),
Average2 = g.Average(i => i.Column2)
};
The use of group by here is not very intuitive, but it's probably easier to read than the other solution. Not sure it can be converted to SQL though...

Using GroupBy, Count and Sum in LINQ Lambda Expressions

I have a collection of boxes with the properties weight, volume and owner.
I want to use LINQ to get a summarized list (by owner) of the box information
e.g.
**Owner, Boxes, Total Weight, Total Volume**
Jim, 5, 1430.00, 3.65
George, 2, 37.50, 1.22
Can someone show me how to do this with Lambda expressions?
var ListByOwner = list.GroupBy(l => l.Owner)
.Select(lg =>
new {
Owner = lg.Key,
Boxes = lg.Count(),
TotalWeight = lg.Sum(w => w.Weight),
TotalVolume = lg.Sum(w => w.Volume)
});
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }

LINQ: GroupBy with maximum count in each group

I have a list of duplicate numbers:
Enumerable.Range(1,3).Select(o => Enumerable.Repeat(o, 3)).SelectMany(o => o)
// {1,1,1,2,2,2,3,3,3}
I group them and get quantity of occurance:
Enumerable.Range(1,3).Select(o => Enumerable.Repeat(o, 3)).SelectMany(o => o)
.GroupBy(o => o).Select(o => new { Qty = o.Count(), Num = o.Key })
Qty Num
3 1
3 2
3 3
What I really need is to limit the quantity per group to some number. If the limit is 2 the result for the above grouping would be:
Qty Num
2 1
1 1
2 2
1 2
2 3
1 3
So, if Qty = 10 and limit is 4, the result is 3 rows (4, 4, 2). The Qty of each number is not equal like in example. The specified Qty limit is the same for whole list (doesn't differ based on number).
Thanks
Some of the other answers are making the LINQ query far more complex than it needs to be. Using a foreach loop is certainly faster and more efficient, but the LINQ alternative is still fairly straightforward.
var input = Enumerable.Range(1, 3).SelectMany(x => Enumerable.Repeat(x, 10));
int limit = 4;
var query =
input.GroupBy(x => x)
.SelectMany(g => g.Select((x, i) => new { Val = x, Grp = i / limit }))
.GroupBy(x => x, x => x.Val)
.Select(g => new { Qty = g.Count(), Num = g.Key.Val });
There was a similar question that came up recently asking how to do this in SQL - there's no really elegant solution and unless this is Linq to SQL or Entity Framework (i.e. being translated into a SQL query), I'd really suggest that you not try to solve this problem with Linq and instead write an iterative solution; it's going to be a great deal more efficient and easier to maintain.
That said, if you absolutely must use a set-based ("Linq") method, this is one way you could do it:
var grouped =
from n in nums
group n by n into g
select new { Num = g.Key, Qty = g.Count() };
int maxPerGroup = 2;
var portioned =
from x in grouped
from i in Enumerable.Range(1, grouped.Max(g => g.Qty))
where (x.Qty % maxPerGroup) == (i % maxPerGroup)
let tempQty = (x.Qty / maxPerGroup) == (i / maxPerGroup) ?
(x.Qty % maxPerGroup) : maxPerGroup
select new
{
Num = x.Num,
Qty = (tempQty > 0) ? tempQty : maxPerGroup
};
Compare with the simpler and faster iterative version:
foreach (var g in grouped)
{
int remaining = g.Qty;
while (remaining > 0)
{
int allotted = Math.Min(remaining, maxPerGroup);
yield return new MyGroup(g.Num, allotted);
remaining -= allotted;
}
}
Aaronaught's excellent answer doesn't cover the possibility of getting the best of both worlds... using an extension method to provide an iterative solution.
Untested:
public static IEnumerable<IEnumerable<U>> SplitByMax<T, U>(
this IEnumerable<T> source,
int max,
Func<T, int> maxSelector,
Func<T, int, U> resultSelector
)
{
foreach(T x in source)
{
int number = maxSelector(x);
List<U> result = new List<U>();
do
{
int allotted = Math.Min(number, max);
result.Add(resultSelector(x, allotted));
number -= allotted
} while (number > 0 && max > 0);
yield return result;
}
}
Called by:
var query = grouped.SplitByMax(
10,
o => o.Qty,
(o, i) => new {Num = o.Num, Qty = i}
)
.SelectMany(split => split);

Convert to Lambda expression

I have the following expression
var q = from c in D1
join dp in
(from e in E1
group e by e.ID into g
select new { ID = g.Key, Cnt = g.Count() })
on c.ID
equals dp.ID
into dpp from v in dpp.DefaultIfEmpty()
select new { c.ID, Cnt= v.Cnt ?? 0 };
How can i convert this to Lambda expression?
Here's one way to go. This kind-of matches the above.
var subquery = E1
.GroupBy(e => e.Id)
.Select(g => new { ID = g.Key, Cnt = g.Count()});
//.ToList();
var q = D1
.GroupJoin(
subquery,
c => c.ID,
dp => dp.ID,
(c, g) => new {ID = c.ID, Cnt=g.Any() ? g.First().Cnt : 0 }
)
After refactoring, I came up with this:
var q = D1
.GroupJoin(
E1,
d => d.ID,
e => e.ID,
(d, g) => new {ID = d.ID, Cnt = g.Count()}
);
For comparision, the query comprehension form is:
var q = from d in D1
join e in E1 on d.ID equals e.ID into g
select new {ID = d.ID, Cnt = g.Count()};
Why would you want to convert it?
For complex queries like this one the query syntax you have used here is invariably clearer.

Resources