C# Essentials: Linq for Lists - Sorting, Filtering, and Aggregating Lists Easily
Vložit
- čas přidán 22. 05. 2024
- Having a List for an object is a fairly common occurrence in C#. In fact, most data access systems end with having the data in a List. This video will help you see how to sort, filter, and operate on lists easily and powerfully.
You will see examples both in a Console application and in a Windows Forms application. This practical example dives right into the most important parts of Linq to get you up and running in minutes.
Get the Starter Code: leadmagnets.app/?Resource=Lin...
Mailing List: signup.iamtimcorey.com/
0:00 - Intro
0:43 - demo app walkthrough
3:56 - for each item in the list, do this - foreach loop.
5:24 - sorting the list of items by item property: OrderBy
8:42 - sort the list descending: OrderByDescending
9:29 - sort the list by more than one parameter: ...ThenBy
11:18 - filter the list: Where(bool true)
15:14 - Sum of the countable property of objects in the list
16:20 - combining list methods: Where and Sum
18:29 - using Linq in applications - WinForm app walk-through: (data binding, events)
22:55 - Implementing Linq
6:59 your explanation of lambda expression just blew my mind, I could not wrap my head around it, and in a completely unrelated video, you explained it in 15 seconds. Wow, thank you!
I am glad it was so helpful.
You have great insights about how to teach, level of detail and pace. Thanks.
Thanks for the kind words. I'm glad you enjoy my style of teaching.
Best c# channel hands down. The best part is you do write the code on the fly rather than using clipboard. I really admire that about your channel.
Thank you!
You are very helpful to many new developers. Tutorials like this are very rare. Thank you very very much, you are AWESOME
Thanks for the kind words. I'm glad you found my videos useful.
Such a short and sweet video which explained to me the whole logic of Linq and what this fancy x is and what this arrow meant. I had no idea as how to use Linq before watching your video. Not only that but I understood lambda (funky “arrow”) and your comparison to foreach loop was such a great idea! Thank you so much, Tim! This old video is like a refined and exquisite old wine in the cellar.
I am glad it was helpful.
A great introduction to Linq that explains the concepts with very simple examples and allows you to explore in depth on your own. Many thanks, Tim! You are great as in all of your tutorials that I have watched till now! I really like your teaching style and your pace...
You are most welcome. Thanks for watching.
Following along, one of a kind tutorial for me. It really reflects the real world situation. Thank you, Tim.
You are most welcome. Thanks for watching.
This was excellent. Thinking of the expression as short-hand for a 'foreach' statement finally unlocked understanding these expressions for me. Thank you!
Glad it was helpful!
simply: you are the best!! so clear, so nice, so simple! thank you very much tim for all your efforts for all of us. you are so kind!! be blessed!!
I appreciate the kind words.
Many thanks for this tutorial. This is the first clear tutorial about Linq that I can understand on CZcams. Very simple and well explained. Muchas gracias !
You are welcome.
Tim's channel is the best reference resource for c#!
Thank you!
Nobody does this better, You are awesome Tim! Great explanation!
Thanks, I agree. I think Carly agrees also - czcams.com/video/SaV-6qerkqI/video.html
Your content is SOOOO well done for thinking logically through the building blocks of these abstract topics. Thanks again! Its great that these years old lessons are still relevant and work as shown in current Visual Studio, too. Hashtag magic! Cheers.
You are welcome.
I enjoyed it and will be watching more of your videos. I'm currently learning the basic of C# and your videos have such good explanation and easy to understand. Thank you and hopefully you'll keep uploading.
I'm glad you are learning a lot. Keep it up.
This helped me alot!
Im still new in C# and still learning to work with Lists.
Thanks for the teaching
You are welcome.
I have told you before. You are a great teacher thank you for your work and knowledge.
Thank you!
Excellent tutorial once again ! I really like Tim's explanations.
Awesome!
Wow, after days of scouring the web and looking at tutorials, this really nailed it! Thanks for the content, it really helped me in my school-project :)
Excellent! I’m glad it was helpful.
This video help me a lot in my internship, thanks Tim!
Excellent!
One of the best tutorial I've ever seen. Thanks :)
You are most welcome. Thanks for watching.
Thank you Tim. Very clear and informative video
You are welcome.
I've learnt so many things. Thank you Tim!
You are welcome.
Another awesome video by Tim. Thank you so much.
You are most welcome. Thanks for watching.
Finally an explanation with human language. I write 20 lines of code for a problem then I see one person write
return a.Where(n => !b.Contains(n)).ToArray(); and get the same result.
More lines isn't a bad thing. Do what is most easily readable.
@@IAmTimCorey Amen!
Good stuff, very well explained! Thanks!
Great tutorial, thank you for taking the time to explain!!!
You are welcome.
Thanks Tim, it helped me a lot!!
You are welcome.
You are awesome! Thanks a lot, couldn't be simpler than this.
I am glad it was so helpful to you.
Thanks for sharing really useful videos.You are a very good teacher.
You are most welcome. Thanks for watching.
Excellent, thank you Tim!
Thank you for watching
Thank you so much for this, really well explained!
You are welcome.
Thanks so much for this - I learned nothing, however this was a good thing as it affirms that I know what I am doing and on the right track as a Developer.
You are welcome.
Clarity at last... thank you.
You are welcome.
Thanks Tim, it's a really helpful video.
0:43 - demo app walk through
3:56 - for each item in the list, do this - foreach loop.
5:24 - sorting the list of items by item property: OrderBy
8:42 - sort the list descending: OrderByDescending
9:29 - sort the list by more than one parameter: ...ThenBy
11:18 - filter the list: Where(bool true)
15:14 - Sum of countable property of objects in the list
16:20 - combining list methods: Where and Sum
18:29 - using Linq in applications - WinForm app walk-through: (data binding, events)
22:55 - Implementing Linq
Thanks! I added it to the description.
This helped me out! Thank you, sir!
You are welcome. Glad to be of help.
Very nice tutorial. Thanks
You are welcome.
This helped me a lot! Thank you so much
You are welcome.
It was another helpful video, keep doing videos like this, congratulations
I’m glad you found it helpful.
Good Introduction..Thank You
You are welcome.
that really helped! thanks man!
Glad it helped!
awesome tutor. appriciated.
I am glad you enjoyed it.
¡Gracias!
Thank you!
You are Brilliant Bro
Thank you!
finally someone who is using lambda expressions... love this video
Thanks!
Great video, thanks.
You are welcome.
Tim,
I always enjoy your videos. I do have a question for you. Though I've been programming since 1981, I'm a newbie to C#. I am building a list of legal descriptions and I see two different ways to do it, but I don't know which is most appropriate or if there's a third option that may be better - or if it's simply a choice of style. The way that I implemented it as follows:
foreach (var legal in legals)
{
LegalLocationModel LegalLocation = new();
LegalLocation.AccountNo = LegalDesc.AccountNo;
LegalLocation.DetailID = maxDtl++;
LegalLocation.QTRQTR = legal;
LegalLocation.Section = "";
LegalLocation.TownShip = "";
LegalLocation.Range = "";
LegalLocations.Add(LegalLocation);
}
Alternatively
foreach (var legal in legals)
{
LegalLocations.Add(new LegalLocationModel { AccountNo = LegalDesc.AccountNo, DetailID = maxDtl, QTRQTR = legal, Section = "", TownShip = "", Range = "" });
maxDtl++;
}
Is there a reason that one of these choices is a better choice or is there a third option that may be better than either of them?
Thanks for your insight,
Rocky
Just discovered your channel A.M.A.Z.I.N.G
Welcome aboard! I'm glad you are enjoying the content.
Very nice explanation Sir :-)
Thank you!
This guy is the best :-)
You are too kind.
Thanks a lot. It was really helpful.
You are welcome!
Hello sir we need an updated video of LINQ both method syntax and query syntax. Great video indeed.
Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/
You are Amazing ❤
Thanks!
@@IAmTimCorey i always See those Pro Programmers Solving Problems in one line using the Where or Orderby and i solve it with 10 lines😆 Thanks for teaching me how to do it ❤
Thanks for the video!
One question:
Whats the difference between the following two approachs?
List listOfIntegers = new List{1,2,3,4,10,20,30,40,50};
var smallNumbersApproach1 = from element in listOfIntegers
where element >= 10
select element;
smallNumbersApproach1 = smallNumbersApproach1.ToList();
var smallNumbersApproach2 = listOfIntegers.Where(x => x >= 10).ToList();
The second approach has less allocations and is therefore more efficient.
26:07 I've seen enough of your videos to point out that that copy/paste can be refactored, haha. Love your content.
Yep, it probably can be.
Excellent sir, we want more and more videos
Thanks!
The funky symbol is a lambda expression. Overall, the tutorial is not bad and I like showing the Form UI and LINQ Library.
Thanks!
Hi Tim, Please, whenever you have time would you consider data binding and lists. All data binding options that are available. Thank you in advance.
Thanks Tim, very clear and very helpful. If you have time, would you do a tutorial on Linq Expression trees and/or implementing Repository pattern using ADO.NET or Dapper ORM because most of the tutorials on the web teaches Repository pattern using EF. Thanks in advance!
thank you so much
this better video to learn linq
we need to more video
You are welcome.
Thank you!
You are welcome.
thanks very informative
You're welcome.
Tim, firstly thank you for all of your hard work! I have watched many of your videos and will be trying to catch them all eventually. I enjoy your teaching style and I love the weekly challenges! I've only done two so far but plan to try more of those also.
For my benefit and hopefully others, can you reply with what software you are using so that I can follow along using the same software. You may have mentioned it in your videos but I want to make sure I'm using the exact same if I can. (Currently using a much older .Net installation and command line editor and compiler).
Thank you :)
I use Visual Studio 2017 Enterprise Edition (but Community Edition, which is free, is almost the same). When VS2019 comes out, I will upgrade to it.
Thanks for clearing that up, i was looking at exercise solutions for c# homework thinking i must have missed something.... nope its LINQ syntax! doh! lol
Glad you figured it out.
Hi. Thanks a lot. I do appreciate your tutorial series. Will you be able to make a similar tutorial for caliburn micro? the lists using 'BindableCollection' is not well documented.
The TimCo Retail Manager series uses WPF with Caliburn Micro. I believe it will cover what you are looking for. I also have a WPF playlist that covers Caliburn Micro quite a bit.
Tim, thank you so much for this. Even though this is a much older video, I'll say it again, with your explanation of what each is doing, I absolutely love. If you get a chance to see this maybe you might be able to tell me why my ".Distinct()" isn't working?
Better yet, what I'm trying to do is, I have a list from AD that's showing ("Administrator" with a LastLogon "7/27/2020 12:19:26 AM" from "DC01" )and another ("Administrator" with a LastLogon "8/4/2020 1:10:50 PM" from "DC02").
I'm trying to have the list only display ONE "Administrator" once but only show the "Administrator" with the most recent logon date of "8/4/2020 1:10:50 PM". Kind of need some help with this.
I have C# down pretty good but the trickiness of ASP.net is killing me but finally got my "returns ..." in the right spot after a ton of nested foreach loops. - thanks
It sounds like you want to do a GroupBy on Administrator and then do a Last on the date.
@@IAmTimCorey , thank you for the quick reply. I greatly appreciate it. I'll check that out and reply back when successful :)
Hi Tim , I really enjoyed learning linq query in your video, I have a question out of the context, why you declared the method LoadSamplData() as a static method?
Because it wasn't storing any information, so it did not need to be instantiated.
You can use the class methods without creating new instance of the Class.
Correct - instantiation isn't necessary because we aren't storing data in the class, which makes calling it faster.
Thanks Tim, very useful! Never really used Linq for Lists yet, cause to me it looked somewhat abstract when i see those "massive" statements people do with Entity Framework.
I have a suggestion: What about a Video to get through the "advanced basics" in OOP in relation with WPF and/or concepts like MVC or MVVM. I'm actually a (certified)software developer, but i'm still in a pretty early stage, working on my skills about those things atm, especially with WPF. The problem about all that is, there isn't a real explanation HOW and WHY a developer should use MVC or MVVM and how to get started and what should be kept in mind.
The thing is: You got it, you actually explain things like they are in a very easy to understand way.
Oh, and I'm actually having the problem "navigating" or... associating through a bunch of different lists, keeping objects they each other relate on (companies have jobs f.e., the class company has a property named Jobs from type List, the class Job has a property company from type Company) - So i want to do a simple if statement, if the company selected has still job objects in the other list, there should be an error, otherwise, it can be marked to delete the entry.
if (companyList.ElementAt(lvCompanies.SelectedIndex).Jobs != null)
The Job property IS NULL at the time of execution but it jumps in that if statement anyways, it probably is a really dumb bug but i still didn't find the problem.
(Oh no, I'm sorry for that long comment)
Thanks for the feedback. Where do you upload the full courses? I will definately look caliburn.micro up, but do i really need a framework to begin with MV*? Sometimes it's better to "start" by scratch, like with your log4net tutorial :)
The problem i had was definately more of a logical/design issue in the backend logic, cause the way it was made more of a mess than anything else. Now i restructured everything and I'm only serializing the companylist atm. When i deserialize i go through two for loops cause of the nested List and strip the joblist out from there. works much more cleaner.
Thanks for the suggestion how you would do it!
Well, WPF is really simple to understand in the first look, but those curly braces statements with bindings etc. are definately one of the difficultest things to do, cause of the missing intellisense.
Thanks a lot, i knew that but is a good idea remember one we have time.
You are welcome.
Thanks soso much
You're welcome!
This video was great because it taught me how to programatically throw CVs in the trash if they have less than 9 years of work experience.
Thanks Corey!
I would recommend a bit more care in reviews.
most sane recruiter in ohio
You’re monster sir!
Another great video.
I do have one question. I always retrieve data via stored procedures. In general my assumption is that for performance reasons that filtering the data is always best done in the stored procedure vs. LINQ so that I’m not passing extra data back to my lists. Does the same hold true for sorting? Am I better off sorting my data in my stored procedures or am I better off returning un sorted data to my lists and having LINQ sort them? My question only relates to performance.
Thanks
My philosophy is to use each tool for what they do best. SQL stores, processes, filters, and sorts data as its primary job. Therefore, whenever possible I let SQL do its thing. C# manipulates data in certain ways better than SQL does and it. C# also is better at working with the data once it is loaded into C#. So, I do my initial filtering and sorting in SQL. Then, if I need to further refine things or do any refinement later, I do it in C#.
Thanks for the great explanation you really make things easy to understand especially for beginners like me. I just finished watching the dapper video you made (How to connect C# to SQL (the easy way)) and now this leaves me with a few questions. So if dapper can execute SQL queries why is LINQ needed? For example, here you used order by but can't that be executed with an SQL query using Dapper? In what ways are LINQ and Dapper similar / different?
I'm not sure if I'm making any sense to be honest. Would appreciate if you could explain this to me please. Thanks
LINQ is used to perform queries on sets of objects in C#. So, let's say you load all of the users from the database. Then, you could filter to only the active users inside of C# for one list and all of the inactive users for another list. You would only need to perform one query of SQL but you could use LINQ to pull out different sets of data out of that one superset.
@@IAmTimCorey It makes much more sense now. Thanks for taking the time to reply, much appreciated.
Hey Tim, great content. Is there a place we can download the structure for this demo?
Not for this one, sorry.
Hay lắm anh trai. Thank kiu anh
You are welcome.
Thanks.
You're welcome
Hello sir, i really appreciate what you do and how you do it! Salute to you, sir. I am a junior developer and building mainly desktop apps. i need to learn "How to manage Many to many " relationship data.
and how to get data from such table............... Please make such a video...
I will add it to the list. Thanks for the suggestion.
I second this! Especially implementing good views for this, and actions that work cascadingly with linked classes (fe displaying, editing or deleting class student with courses (not to be removed) and grades). Scaffolding always excludes these groups but in an application i often want to include them.
@@IAmTimCorey thank you
So what is it in C# when there is .WhereEquals and .Select etc?? Can do it on a QueryObject, but is that LINQ as well? Trying to find out what to learn, this video didn't seem to cover that stuff. Anyone got any suggestions? Thanks!
so useful
I'm glad.
Hi Corey, the content is spot on please share the code repository url.
I link to the code in the description of my videos. If there is no link, I don't have the source code anymore. Sorry.
I tried to replicate this application, so that I could run it myself. I referenced the class library and also added the directive the way you had taught in the ConsignmentShop tutorial. But for some reason in my Dashboard class, the "using LinqLibrary" directive would not be recognized. There was an auto suggestion to fix it which replaced the "using LinqLibrary" with "using ConsoleUI" and that resolved it, but I don't understand why?
Thak you very much Sir, I have a problem, I want to know how to pass an object (included in ListBox) to another form after select the item.
Request that object in the form's constructor.
This is a great video. Thanks.
I watched it because I wasn't sure what LINQ actually was. I had the misconception that somehow LINQ was more complicated than regular C# and expected LINQ to have a unique syntax of its own. Now I realize I'd seen examples like this before without realizing it was using LINQ!
I was, though, a little surprised you copied that line instead of immediately refactoring the code to avoid the duplication. Is DRY ("Don't Repeat Yourself") a valuable practice to follow?
So you can use the more complicated "SQL-like" LINQ statements (from...where...select...) but a lot is built into the lists, which makes it really easy. As for not refactoring to keep something DRY, this is a demo of LINQ and while I try to follow best practices and show those off while I'm doing other things, I have to maintain a balance in a demo. If I show off refactoring to keep something DRY, will it be beneficial to the viewer and does that benefit outweigh the extra time and complexity it will incur. In this case I decided to reduce the complexity and time to focus just on LINQ.
Fair enough.
Is it possible to do this with dapper?
Any chance on getting an updated video on this topic?
Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/
Thank you for your lesson. Very useful!
But 1 question: How to return the original list after filter by linQ?
With a List, you return a new List. If you want to sort an existing list, you would need to use a different list type.
IAmTimCorey So if I want to call a list from another class that’s inside a method inside Program.cs I should put that list again in a new list? Or how do I get the contents of the list inside memory? In the other class I use CSV helper to read a CSV file and put the contents into a list. This list I want to call inside Program.cs to load default users.
Hello Tim.
I find myself very often in situation when I want to use foreach loop and then do something with the item form that list (collection) Lets say List. As you know, you can't really do that.
I find that I have to make copies of lists and do all kind s of crazy workarounds that does not feel very efficient.
Could you suggest best practice here?
When looping over objects, you cannot modify the list without causing issues. So, you need to look at what you are really trying to do. There is usually a different way to accomplish the same thing. Maybe use a LINQ query to transform the list (filtering with a where clause). You are on the right track with your question for sure. Now you just need to keep poking at it until you come up with something better. For now, though, it does work which is a good first step.
too helpfull!
I am glad.
I know this may be a silly question. Again thank for another great lesson Tim. But your Program.cs file within your FormUI console is that file blank or does it have any relative code? I was following you along on Visual Studio Code and was coming across a debugging error where it said my Program.cs file within the FormUI console had no static Main method. (Which is because I was displaying my output within the ConsoleUI. I had to delete the FormUI console app template entirely to run my program.
Here is my real question: Would my project have run if I created a Dashboard.cs[design] file and followed along with that portion of the video? Leaving the Program.cs file blank?
Again thank you for another great video.
The answer: Program.cs is where you initialized the form.
P.S. Can we get a video on creating web applications within Visual Studio Code vs Visual Studio 2022. Your video on coding C# within Visual Studio Code was superb!
ListManager class was static one when i'm trying to access that class facing protection level error
Probably your Person class is internal instead of public. Make them all public to follow along this demo.
How did you make that year picker (Basically a number picker) in the form application. I couldn't find such a control ;)
Not sure which one I used, but this would probably work: github.com/alex-titarenko/wpfcontrols
There has to be a better way to update bindings other than having to remember to duplicate the line of linq code, right? Thanks for the videos, very helpful!
Thanks for the reply Tim. I'd be interested to see the video of the bindinglist, if only for clarity and exploration.
Thx sir
You are welcome.
Is it a good idea to get the data from the database at the first time, then we filter it just by using lists (LINQ) instead of getting the filtered data from the database directly?
It depends on the situation. Typically though, the database is best at handling data, including filtering and sorting. That is what it is designed to do. A C# application will never be as efficient at SQL at filtering data. However, that assumes one client and one SQL Server. If you have 100,000 clients to one underpowered SQL Server, you might find that the overall performance is better if you bring the raw data down to the clients first. In general, though, that isn't the case. I default to letting SQL do data and then, once I have the data, I do any further refinements to it if I need to (that the initial call didn't anticipate).
How can I sort List by its value, that is by the size/count of the List in the KeyValuePair?
You can do it. Take it one step at a time. Make a query for just the KVP (forget that it is in a list for a minute). Then, once you have figured out that query, figure out how to do the same thing inside of a list.
@@IAmTimCorey Thank you very much sir.
In UpdateBinding you used x.YearsExperience >=5, which is hardcoded, how come your list is still updated based on your selection?
The number of years of experience is hard-coded, but which items meet that criterion changes as we change their YearsExperience value. So, when I change Sue's experience from 1 year (not showing in the list) to 15 years, she shows up on the list because she has more than 5 years of experience now.
Do you a git reposiity for the ConsoleUI, FormUI and LinqLibrary code?
I do not, sorry.
Please i cant find how to get the c# fundamentals, i need help on that, i have searched and still cant find videos related to that, thanks.
Here you go: www.iamtimcorey.com/blog/49797/how-to-learn-csharp-well
Great
Thanks.
Just 1 Q, about returning List:
It's nice to see someone else do that. But, isn't it important to return a List clone?
return new List(output); // That was just something I learned early on.
It was said that, if you return output;, then you're returning a reference to that local List instead of setting your external List to those contents.
You are returning the list but typically that is what you want. Making a copy of the list duplicates the memory but doesn't usually add value. Unless you find that you want to manipulate the list in the calling class and the called class separately, just use the same list.