LINQ LEFT JOIN not working on NULL values - c#

I have two tables Student and Marks.
Student table have the following fields:
StudentID,Name,MarkID(Nullable).
Marks table have the following fields:
MarkID,Mark
Student table
StudentID Name MarkID
1 Mark 1
2 Mike NULL
3 John NULL
4 Paul 2
Mark table
MarkID Mark
1 80
2 100
If I use the left join then i getting only mark and paul records.
I want all the records in the left table(Student)
My Query is:
var query = (from s in Students
join m in Marks on s.MarkID equals m.MarkID
into mar from subMark in mar.DefaultIfEmpty()
where(m.Mark > 80)
Select s.Name)
.ToList()
Note: It is an Example only.
While joining two tables using left join and applying where condition on the second table ,If joined column value is null in first table,it won't bring the record from first table.

NULL comparisons are always false. That's the way SQL's three-valued logic works. If you want to match rows where the values are both null you should use a statement that checks both of them for null.
In a SQL statement you would write:
ON S.MARKID=M.MARKID OR (S.MARKID IS NULL AND M.MARKID IS NULL)
In C# you can use the comparison operator and your LINQ provider will convert this to IS NULL, eg:
on s.MarkID == m.MarkID || (s.MarkID == null && m.MarkID==null)

The problem is we use the where clause in Left join.So it will discard the null value records.
var sampleQuery= (from f in food
join j in juice on f.ID equals j.ID into juiceDetails from juice in juiceDetails.DefaultIfEmpty()
where(!j.deleted)
join fr in fruit on f.ID equals fr.ID into fruitDetails from fruit in fruitDetails.DefaultIfEmpty()
where(!fr.deleted)
select new
{
// codes
});
Instead of this we have to check the where clause in table itself.Like this
var sampleQuery= (from f in food
join j in juice.Table().where(x=>!x.deleted) on f.ID equals j.ID into juiceDetails from juice in juiceDetails.DefaultIfEmpty()
join fr in fruit.Table().where(x=>!x.deleted) on f.ID equals fr.ID into fruitDetails from fruit in fruitDetails.DefaultIfEmpty()
select new
{
// codes
});
It will work fine.
Thank you.

/EDIT: My first answer was using a FULL OUTER JOIN. this was way over the top and probably wrong or not compleltly correct.
The new answer uses a LEFT OUTER JOIN. I have created some sample data using LinqPad to get a working example. Ignore the .Dump() method if you are not using LinqPad.
var Students = new List<Student>() {
new Student() {StudentId = 1, Name ="John", MarkId = 1},
new Student() {StudentId = 1, Name ="Paul", MarkId = 1},
new Student() {StudentId = 1, Name ="Steve", MarkId = 1},
new Student() {StudentId = 1, Name ="John", MarkId = 2},
new Student() {StudentId = 1, Name ="Paul", MarkId = 3},
new Student() {StudentId = 1, Name ="Steve", MarkId = 1},
new Student() {StudentId = 1, Name ="Paul", MarkId = 3},
new Student() {StudentId = 1, Name ="John" },
new Student() {StudentId = 1, Name ="Steve" },
new Student() {StudentId = 1, Name ="John", MarkId = 1}
};
var Marks = new List<Mark>() {
new Mark() {MarkId = 1, Value = 60},
new Mark() {MarkId = 2, Value = 80},
new Mark() {MarkId = 3, Value = 100}
};
var StudentMarks = Students
.GroupJoin(
Marks,
st => st.MarkId,
mk => mk.MarkId,
(x,y) => new {
StudentId = x.StudentId,
Name = x.Name,
Mark = y.Select (z => z.Value).SingleOrDefault()
}
)
.Dump();
}
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public int MarkId { get; set; }
}
public class Mark
{
public int MarkId { get; set; }
public int Value { get; set; }
}
Output:
As you cann see in my Students list, there a 2 students without a MarkId. Those 2 get the default value assigned due to .SingleOrDefault(). I think this will solve your problem and gives you a good basis for further fiddeling.
references:
How do you perform a left outer join using linq extension methods

In your query you have written From in your Join statement while joining it.
Instead you should use in::
from s in Students
join m in Marks on s.MarkID equals m.ID into mar
from subMark in mar.DefaultIfEmpty()
Select s.Name).ToList()

I had the same problem. This solution only works if you have at least one row in subMark. The rows' ID doesn't matter.
var query = (from s in Students
join m in Marks on s.MarkID equals m.MarkID into fullM
into mar from subMark in mar.DefaultIfEmpty()
where(m.Mark > 80)
Select s.Name)
.ToList()
the keyword into does the magic. Adding it shows all rows, also those, which have NULL-Values in mar.

Related

Select TOP 1 for each FK in list using Entity Framework

I have a large table where I'm trying to select the top 1 row for each FK in a list.
My table is laid out as:
ChangeId | AssetId | Timestamp
1 1 123
2 2 999
3 1 3478
4 3 344
5 2 1092
Where ChangeId is my PK, AssetId is my FK and Timestamp is the value I'm trying to select.
If I try the following:
var results =
from Asset in _context.Asset
join change in _context.Change on Asset.AssetId equals change.AssetId into potentialChange
from actualChange in potentialChange.OrderByDescending(y => y.ChangeId).Take(1)
select
{
AssetId,
Timestamp
}
Where my expected result would be:
[
{
AssetId: 1,
Timestamp: 3478
},
{
AssetId: 2,
Timestamp: 1092
},
{
AssetId: 3,
Timestamp: 344
}
]
This query flags up the The LINQ expression could not be translated and will be evaluated locally. which is not suitable for a production rollout.
Running a foreach loop and selecting each item out 1 by 1 works, not it's not a performant solution.
Is there a suitable way to achieve the above?
Try to group it by AssetId and take max from each group
var results =
from Asset in _context.Asset
join change in _context.Change on Asset.AssetId equals change.AssetId into potentialChange
group potentialChange by potentialCharge.AssetId into g
select
{
g.Key,
g.Max().Timestamp
}
Use Group By as follows:
List<MyTable> data = new List<MyTable>()
{
new MyTable(){ChangeId = 1, AssetId = 1, Timestamp = 123},
new MyTable(){ChangeId = 2, AssetId = 2, Timestamp = 999},
new MyTable(){ChangeId = 3, AssetId = 1, Timestamp = 123},
new MyTable(){ChangeId = 5, AssetId = 3, Timestamp = 123},
new MyTable(){ChangeId = 5, AssetId = 2, Timestamp = 123},
};
var expectedData = data.OrderByDescending(d => d.Timestamp).GroupBy(d => d.AssetId).Select(g => new
{
AssetId = g.Key,
TimeStamp = g.First().Timestamp
}).ToList();
This will give your expected result.
Try using .First() instead of .Take(1)
LINQ How to take one record and skip rest c#

LINQ OrderBy based on row values

Lets say we have two tables Parent "DocumentCodes" and Child "Documents".
DocumentCodes table have columns DID,DocumentName,PrintOrder and AscOrDesc
Documents table have columns ID,DID and EffectiveDate.We are getting datatable by joining these two tables.
We need to sort this datatable based on below rules.
Sort By "PrintOrder" column ascending.
If two or more rows have similar "DocumentNames" value then sort by "EffeciveDate" ascending or descending based on "AscOrDesc" value.
"AscOrDesc" column accepts only 'A' or 'D'. If value is 'A' we need to sort "EffectiveDate" ascending and if value is 'D' we need to sort "EffectiveDate" descending.
For example,
DocumentCodes
DID DocumentName PrintOrder AscOrDesc
1 Test1 1 D
2 Test2 2 A
3 Test3 3 D
Documents
ID DID EffectiveDate
1 2 7/9/2017
2 1 5/5/2017
3 2 7/8/2017
4 3 4/9/2017
After joining above two tables. We have DataTable.
ID DocumentName EffectiveDate PrintOrder AscOrDesc
1 Test2 7/9/2017 2 A
2 Test1 5/5/2017 1 D
3 Test2 7/8/2017 2 A
4 Test3 4/9/2017 3 D
Now After sorting this DataTable by using above rules. DataTable should look like this.
ID DocumentName EffectiveDate PrintOrder AscOrDesc
1 Test1 5/5/2017 1 D
2 Test2 7/8/2017 2 A
3 Test2 7/9/2017 2 A
4 Test3 4/9/2017 3 D
Note: EffectiveDate is in MM/DD/YYYY format.
I tried with below code but its not working.
var records2 = from q in datatable.AsEnumerable()
let sortorder= q.Field<string>("AscOrDesc") == "A" ?
"q.Field<DateTime>(\"EffectiveDate\") ascending":
"q.Field<DateTime>(\"EffectiveDate\") descending"
orderby q.Field<int>("PrintOrder"),sortorder
select q;
what I am doing wrong in above code ?
The situation is a fairly ugly one, given that two result rows could theoretically be compared which have the same PrintOrder but different AscOrDesc values. It's only the source of the data that's preventing that.
I do have a horrible hack that I believe should work, but I'm really not proud of it. Basically, imagine that the date is a number... ordering by descending date is equivalent to ordering by the negation of the "date number". For DateTime, we can just take the Ticks value, leading to:
var records2 = from q in datatable.AsEnumerable()
let ticks = q.Field<DateTime>("EffectiveDate").Ticks *
(q.Field<string>("AscOrDesc") == "A" ? 1 : -1)
orderby q.Field<int>("PrintOrder"), ticks
select q;
Ugly as heck, but it should work...
Pretty ugly, but couldnt figure out something better that fits your needs.
Maybe you have luck and #JonSkeet will come by again. :)
(Used LINQ To Object you would need to rewrite it fit your LINQ to SQL)
static void Main(string[] args)
{
var lstFoos = new List<Foo>() {
new Foo() { Id = 1, DocumentName = "Test2", EffectiveDate = new DateTime(2017, 7, 9), PrintOrder = 2, AscOrDesc = "A" },
new Foo() { Id = 2, DocumentName = "Test1", EffectiveDate = new DateTime(2017, 5, 5), PrintOrder = 1, AscOrDesc = "D" },
new Foo() { Id = 3, DocumentName = "Test2", EffectiveDate = new DateTime(2017, 7, 8), PrintOrder = 2, AscOrDesc = "A" },
new Foo() { Id = 4, DocumentName = "Test3", EffectiveDate = new DateTime(2017, 4, 9), PrintOrder = 3, AscOrDesc = "D" },
};
var result = lstFoos.OrderBy(x => x.PrintOrder).GroupBy(x => x.DocumentName).SelectMany(x =>
{
if (x.Count() > 1)
{
var ascOrDesc = x.First().AscOrDesc;
return new List<Foo>(ascOrDesc == "A" ? x.OrderBy(y => y.EffectiveDate) : x.OrderByDescending(y => y.EffectiveDate));
}
return new List<Foo>() {x.First()};
});
foreach (var foo in result)
Console.WriteLine(foo.ToString());
Console.ReadLine();
}
public class Foo
{
public int Id { get; set; }
public string DocumentName { get; set; }
public DateTime EffectiveDate { get; set; }
public int PrintOrder { get; set; }
public string AscOrDesc { get; set; }
public override string ToString()
{
return $"Id: {Id} | DocumentName: {DocumentName} | EffectiveDate: {EffectiveDate} | PrintOrder: {PrintOrder} | AscOrDesc: {AscOrDesc}";
}
}
Looks like a TYPO, Hope this works
var records2 = from q in datatable.AsEnumerable()
orderby q.Field<int>("PrintOrder")
orderby q.Field<string>("AscOrDesc") == "A" ? q.Field<DateTime>("EffectiveDate") : q.Field<DateTime>("EffectiveDate") descending
select q;
Usually my statement used to be like this
var result = from q in datatable.AsEnumerable()
orderby q.PrintOrder
orderby q.AscOrDesc== "A" ? q.EffectiveDate: q.EffectiveDate descending
select q;

Using LINQ to get information from two tables, with a join

I have a linq statement to populate two labels. The thing is, this information comes from two tables. I Have a join to join the two tables, except i cant get my Terms and Conditions from my Campaign table. Its only picking up the RedemptionLog table columns. Anyone to help with this?
MSCDatabaseDataContext MSCDB = new MSCDatabaseDataContext();
var q = from row in MSCDB.Tbl_RedemptionLogs
join d in MSCDB.Tbl_Campaigns on row.CampaignId equals d.CampaignId
orderby row.VoucherCode descending
select row;
var SeshVoucherDisplay = q.First();
lblCode.Text = SeshVoucherDisplay.VoucherCode;
lblTerms.Text = SeshVoucherDisplay
For the SeshVoucherDisplay variable, it only picks up from the RedemptionLogs table, yet i did a join? Any help?
Try something like this :
var SupJoin = from row in MSCDB.Tbl_RedemptionLogs
join d in MSCDB.Tbl_Campaigns on row.CampaignId equals d.CampaignId
orderby row.VoucherCode descending
select new { Id = row.ID, SupplierName = row.SupplierName,
CustomerName = d.CompanyName };
The column names are just for example purpose. Put your own there. And thereafter, you can apply First on it and use that particular variable.
Hope this helps.
Well, by writing select row you asked LINQ to give back to you only row.
If you want both elements, you need to ask for both of them, e.g. by writing select new { row, d }.
In this example
var foo =
new []
{
new { Id = 1, Name = "a" },
new { Id = 2, Name = "b" },
new { Id = 3, Name = "c" }
};
var bar =
new []
{
new { Id = 1, Name = "d" },
new { Id = 2, Name = "e" },
new { Id = 3, Name = "f" }
};
var baz =
from a in foo
join b in bar on a.Id equals b.Id
select new { a, b };
var qux =
from a in foo
join b in bar on a.Id equals b.Id
select new { a, b };
In baz you'll find only a list of foos, in qux you'll find a list of both foos and their bar.
Try this:
var query = (from row in MSCDB.Tbl_RedemptionLogs
join d in MSCDB.Tbl_Campaigns on row.CampaignId equals d.CampaignId)
orderby row.VoucherCode descending
select new
{
columnname = row.columnname
});
When writing select row you relate to the row you defined in from row in MSCDB.Tbl_RedemptionLogs.
However if you want the data from both tables you have to write something similar to this:
select new {
// the properties of row
Redemption = row.redemption,
// the properties of d
Campaign = d.CampaignID // alternativly use may also use row.CampaignID, but I wanted to show you may acces all the members from d also
}

Multiple outer join using Linq with 2 joins to the same table/object. Got the SQL, need the Linq to Entity

I am trying to reproduce the following SQL query in Linq and need some help please.
select
dbo.Documents.DocId,
dbo.Documents.ReykerAccountRef,
dbo.Documents.ReykerClientId DocClientID,
CAAs.ClientId CAAClientIDCheck,
ClientData.FullName ClientFullName,
CAAs.IFAId,
AdvisorData.FullName AdvisorFullName
from dbo.Documents
left join
dbo.CAAs on dbo.Documents.ReykerAccountRef = dbo.CAAs.AccountRef
left join
dbo.hmsProfileDatas AS ClientData
on
dbo.CAAs.ClientId = ClientData.ReykerClientID
left join
dbo.hmsProfileDatas AS AdvisorData
on
dbo.CAAs.IFAId = AdvisorData.ReykerClientID
I am trying to link to the same table twice, once for a client fullname and the other for an Advisor fullname.
The basic sql I want to produce in linq is
select table1.*,table2.*,a.Fullname, b.Fullname
from table1
left join
table2 on table1.t2Id = table2.Id
left join
table3 AS a
on
table2.t3Id1 = table3.id1
left join
table3 AS b
on
table2.t3Id2 = table3.id2
So table one is joined to table2 and table2 has 2 foreign keys (t3Id1 and t3Id2) to table3 to different fields (id1 and id2).
This is what I have tried following some guidance, but it's not returning anything! What's going wrong?
var results3 = from doc in DataContext.Documents
from caa
in DataContext.CAAs
.Where(c => c.AccountRef == doc.ReykerAccountRef)
.DefaultIfEmpty()
from cpd
in DataContext.hmsProfileDatas
.Where(pdc => pdc.ReykerClientID == caa.ClientId)
.DefaultIfEmpty()
from apd
in DataContext.hmsProfileDatas
.Where(pda => pda.ReykerClientID == caa.IFAId)
.DefaultIfEmpty()
select new DocumentInList()
{
DocId = doc.DocId,
DocTitle = doc.DocTitle,
ReykerDocumentRef = doc.ReykerDocumentRef,
ReykerAccountRef = doc.ReykerAccountRef,
ClientFullName = cpd.FullName,
AdvisorFullName = apd.FullName,
DocTypeId = doc.DocTypeId,
DocTypes = doc.DocTypes,
DocDate = doc.DocDate,
BlobDocName = doc.BlobDocName,
UploadDate = doc.UploadDate,
};
I hope I understood your example correctly. Here's another simple example, that should give what you need:
private class User
{
public int UserId;
public string Name;
public int GroupId;
public int CollectionId;
}
public class Group
{
public int GroupId;
public string Name;
}
public class Collection
{
public int CollectionId;
public string Name;
}
static void Main()
{
var groups = new[] {
new Group { GroupId = 1, Name = "Members" },
new Group { GroupId = 2, Name = "Administrators" }
};
var collections = new[] {
new Collection { CollectionId = 1, Name = "Teenagers" },
new Collection { CollectionId = 2, Name = "Seniors" }
};
var users = new[] {
new User { UserId = 1, Name = "Ivan", GroupId = 1, CollectionId = 1 },
new User { UserId = 2, Name = "Peter", GroupId = 1, CollectionId = 2 },
new User { UserId = 3, Name = "Stan", GroupId = 2, CollectionId = 1 },
new User { UserId = 4, Name = "Dan", GroupId = 2, CollectionId = 2 },
new User { UserId = 5, Name = "Vlad", GroupId = 5, CollectionId = 2 },
new User { UserId = 6, Name = "Greg", GroupId = 2, CollectionId = 4 },
new User { UserId = 6, Name = "Arni", GroupId = 3, CollectionId = 3 },
};
var results = from u in users
join g in groups on u.GroupId equals g.GroupId into ug
from g in ug.DefaultIfEmpty()
join c in collections on u.CollectionId equals c.CollectionId into uc
from c in uc.DefaultIfEmpty()
select new {
UserName = u.Name,
GroupName = g != null ? g.Name : "<No group>",
CollectionName = c != null ? c.Name : "<No collection>"
};
}
It produces two join over one table to get data from other two tables.
Here's the output:
Ivan Members Teenagers
Peter Members Seniors
Stan Administrators Teenagers
Dan Administrators Seniors
Vlad <No group> Seniors
Greg Administrators <No collection>
Arni <No group> <No collection>

How to re-write this inner join subquery from SQL to Lambda

SELECT ulcch.ID, ulcch.UserLoginHistoryID, ulcch.StatusID,
ulcch.ClientModuleID, ulcch.DeviceState, ulcch.UpdatedAt, ulcch.CreatedAt
FROM UserLoginClientConnectionHistory AS ulcch INNER JOIN
(SELECT MAX(CreatedAt) AS maxCreatedAt
FROM UserLoginClientConnectionHistory AS ulcch1
GROUP BY UserLoginHistoryID) AS m ON m.maxCreatedAt = ulcch.CreatedAt
There can be many updates of 'device state' per day audited into this login table. This query returns the last unique one for each day.
I would like this re-written as a Lambda statement. This is how far I got, I don't know if i'm on the right track, and my Max() is throwing a type error, probably because the group by is making another list or something...
Hope you can work it out from my object examples.... :S
userLogin.UserLoginClientConnectionHistories.Where(x => x.CreatedAt ==
userLoginClientConnectionHistoryRepository.GetAll(
GenericStatus.Active).GroupBy(y => y.UserLoginHistoryID).Max(y => y.CreatedAt));
I think this does what you want:
var result = userLogin.UserLoginClientConnectionHistories
.GroupBy(y => new { Id = y.UserLoginHistoryID, Day = y.CreatedAt.Date })
.Select(x => new
{
Id = x.Key.Id,
Day = x.Key.Day,
MostRecent = x.Max(y => y.CreatedAt)
});
Here is a testbed for it:
public class Program
{
class LoginEntry
{
public int UserLoginHistoryID { get; set; }
public DateTime CreatedAt { get; set; }
}
class UserLogin
{
public List<LoginEntry> UserLoginClientConnectionHistories = new List<LoginEntry>();
}
public static void Main(string[] args)
{
UserLogin userLogin = new UserLogin();
userLogin.UserLoginClientConnectionHistories = new List<LoginEntry> {
new LoginEntry {UserLoginHistoryID = 1, CreatedAt = new DateTime(2009, 1, 1, 3, 0 ,0)},
new LoginEntry {UserLoginHistoryID = 1, CreatedAt = new DateTime(2009, 1, 1, 15, 0 ,0)},
new LoginEntry {UserLoginHistoryID = 1, CreatedAt = new DateTime(2009, 1, 3, 11, 0 ,0)},
new LoginEntry {UserLoginHistoryID = 1, CreatedAt = new DateTime(2009, 1, 1, 10, 0 ,0)},
new LoginEntry {UserLoginHistoryID = 2, CreatedAt = new DateTime(2009, 1, 3, 4, 0 ,0)},
new LoginEntry {UserLoginHistoryID = 2, CreatedAt = new DateTime(2009, 1, 3, 5, 0 ,0)},
};
var result = userLogin.UserLoginClientConnectionHistories
.GroupBy(y => new { Id = y.UserLoginHistoryID, Day = y.CreatedAt.Date })
.Select(x => new
{
Id = x.Key.Id,
Day = x.Key.Day,
MostRecent = x.Max(y => y.CreatedAt)
});
foreach (var item in result)
{
Console.WriteLine("User {0}, day {1}, most recent {2}",
item.Id,
item.Day,
item.MostRecent);
}
}
}
Output:
User 1, day 01-01-2009 00:00:00, most recent 01-01-2009 15:00:00
User 1, day 03-01-2009 00:00:00, most recent 03-01-2009 11:00:00
User 2, day 03-01-2009 00:00:00, most recent 03-01-2009 05:00:00
Here is the inner join portion as a lambda. I assumed CreatedAt was a dateTime.
UserLoginClientConnectionHistory
.GroupBy (ulcch1 =>
new
{
Name = ulcch1.Name
})
.Select (g =>
new
{
maxCreatedAt = (DateTime?)(g.Max (p => p.CreatedAt))
})
I think you want to group by CreatedAt rather than UserLoginHistoryID:
var q = userLogin.UserLoginClientConnectionHistories
.GroupBy(h => h.CreatedAt)
.OrderByDescending(g => g.Key) // Sort by CreatedAt
.First()
.Select(h => new { h.Id, h.UserLoginHistoryID, ... });
This will return the set of UserLoginClientConnectionHistory entries that share the most recent CreatedAt value.
Thanks for all your help guys, i've voted you all up, but you wouldn't believe it but a few hours later I searched for a program to convert SQL to LINQ, and to my surprise found one called "Linqer". Sounds crazy and didn't expect to get far, but it worked perfectly.. definitely worth checking out that app if anyone else gets stuck in the same boat...
Check the mammoth query it returned! After analysing it, don't think it's got extra bloat? Anyone have any optimisation tips or spot any unnecessary code?
moduleDeviceStates = from ulh in user.UserLoginHistories
join ulcch in userLogin.UserLoginClientConnectionHistories on new { ID = ulh.ID } equals new { ID = ulcch.UserLoginHistoryID }
join cm in clientModuleRepository.GetAll(GenericStatus.Active) on new { ClientModuleID = ulcch.ClientModuleID } equals new { ClientModuleID = cm.ID }
join mo in moduleRepository.GetAll(GenericStatus.Active) on new { ModuleID = cm.ModuleID } equals new { ModuleID = mo.ID }
join m in
(
(from ulcch1 in userLogin.UserLoginClientConnectionHistories
group ulcch1 by new
{
ulcch1.UserLoginHistoryID
} into g
select new
{
maxCreatedAt = g.Max(p => p.CreatedAt)
})) on new { maxCreatedAt = ulcch.CreatedAt } equals new { maxCreatedAt = m.maxCreatedAt }
select new ModuleDeviceState()
{
ModuleID = mo.ID,
Name = mo.Name,
DeviceState = (State.DeviceState)ulcch.DeviceState,
CreatedAt = ulcch.CreatedAt
};
Cheers for your help dahlbyk, but I did want to group on UserLoginHistoryID, I had my query confirmed in SQL before delving into a lambda equivalent :) thanks.
#Mark Thanks for taking the time to reply, yes I do what the [last] entries per user (userloginhistory.. which in turn contains a userID) for each day, and exporting my sql into the linq query did produce what I wanted (which can be seen in the query result below; this is what I want. The reason you see double entries for each day is because there are also attached ClientModule's.. so I really want all client module, per login entry per day - so hard to get a programming requirement across over a discussion forum argh!) Perhaps yours does exactly the same thing (it appears to if I am reading your output correctly) just a lot more streamlined.
See I didn't know too much about the anon casting you've done there with GroupBy and Select, but now I see it, it makes sense. I might give yours a go. Hopefully I can give it a tweak to include distinct ClientModule's per day too. So anyway.. here is the query result from my SQL, and effectively what I got through my own lambda:
ID UserLoginHistoryID StatusID ClientModuleID DeviceState UpdatedAt CreatedAt
277 62 1 1 4 NULL 2009-10-31 13:28:59.003
278 62 1 16 4 NULL 2009-10-31 13:28:59.003
331 65 1 1 4 NULL 2009-10-31 17:13:28.333
332 65 1 16 4 NULL 2009-10-31 17:13:28.333
Update Mark: Hi again, well after a couple of tweaks on your query, I could produce the same object graph in .NET between both lambda statements. This is the one I will use now, derived from yours as it's more streamlined and easier to understand than the auto-gen'd one and I will award you the points :)
I added a few more entries to the Group By as I need that for my new ModuleDeviceState class.
moduleDeviceStates = userLogin.UserLoginClientConnectionHistories
.GroupBy(y => new { Id = y.UserLoginHistoryID,
CreatedAt = y.CreatedAt.Date,
ModuleID = y.ClientModule.ModuleID,
ModuleName = y.ClientModule.Module.Name,
DeviceState = y.DeviceState })
.Select(x => new ModuleDeviceState()
{
ModuleID = x.Key.ModuleID,
Name = x.Key.ModuleName,
DeviceState = (State.DeviceState)x.Key.DeviceState,
CreatedAt = x.Max(y => y.CreatedAt)
});

Categories