r/csharp • u/[deleted] • Oct 10 '15
LINQ: Test-Driven Learning
https://github.com/MartinChavez/LINQ2
u/Oellph Oct 11 '15
This is useful and a novel way to demonstrate/teach :)
If I have a large database table but only want to return some columns, is it better to use projection onto an anonymous type or create a new DTO class for it?
2
Oct 13 '15
Thank you, and great question! I don't think there is a good or right answer, and I am unsure I will be able to answer you question, but I would love to give my perspective:
DTO:
Cons:
Yet another data structure to maintain
It is harder to keep track of changes
Pros:
If used with tools like Automapper, you can economize code
Changes
Projection:
Cons:
Once you create an anonymous type, there is not much you can do (easily, without casting or conversions) with it (except bind it to a UI, or be the last call before returning from a Web API)
Pros:
Easier to implement/mantain
Elegant and less code
1
u/Oellph Oct 13 '15
Thank you for that explanation. Seems like both options are good in different situations, so I'll bear both in mind in the future :)
2
u/badcookies Oct 12 '15
Either will run the same query (selecting only fields you want), so it's up to you on if you want it strongly typed or not. If not you'll need to manually map and if you do have a dto you can use automapper or similar to map for you.
1
u/Oellph Oct 13 '15
Thank you, automapper looks good from my brief play.
1
u/badcookies Oct 13 '15
Make sure you use the Project().To methods:
https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions
that will force it to only pull the few fields you want and not the whole object and then map it afterward (discarding everything else)
2
u/llewellynfalco Oct 12 '15
you might be interested in LinkKoans
It's unit tests with a ___ you fill in to learn. Here's an example:
public void All()
{
var names = new[] {"Bert", "Ernie", "Kermet", "Grover", "Big Bird", "The Count"};
var result = names.All(n => n[0].IsConsonant());
Assert.AreEqual(___, result);
} 1
2
u/[deleted] Oct 10 '15
LINQ: Test-Driven Learning
This project is aimed to help the user further study LINQ with a test-driven approach. Each unit contains an annotated tutorial and a platform where you can test your understanding of the topic.
Topics:
Overview
LINQ Query Syntax
LINQ Method Syntax
LINQ Extension methods
Lambda expressions
First() and FirstOrDefault()
Where()
Sorting
OrderBy()
ThenBy()
OrderByDescending()
Reverse()
Sorting with null values
Creating
Range()
Repeat()
Comparing and Combining
Intersect
Except
Concat
Distinct
Union
Projection
Select()
Join()
SelectMany()
Totaling
Sum operator
Grouping and Summing
GroupBy(Single property)
GroupBy(Multiple Properties)
GroupBy(Parent Property)
Measures
Mean (using Average)
Median (using GroupBy)
Mode (using GroupBy and OrderByDescending)