Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select method in List<t> Collection

I have an asp.net application, and now I am using datasets for data manipulation. I recently started to convert this dataset to a List collection. But, in some places it doesn't work. One is that in my old version I am using datarow[] drow = dataset.datatable.select(searchcriteria). But in the List collection there is no method available for finding particular values. Is there any way for me to select some values according with my search criteria? I want to know if this is possible. Please help me.

like image 631
MAC Avatar asked Sep 27 '10 07:09

MAC


People also ask

What is select () in C#?

The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.

How does Linq select work?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.

How do I return a string from a list in C#?

In C# you can simply return List<string> , but you may want to return IEnumerable<string> instead as it allows for lazy evaluation. @Marc: Certainly, but if you return List<string> you don't have the option even with a lazy source.


2 Answers

Well, to start with List<T> does have the FindAll and ConvertAll methods - but the more idiomatic, modern approach is to use LINQ:

// Find all the people older than 30
var query1 = list.Where(person => person.Age > 30);

// Find each person's name
var query2 = list.Select(person => person.Name);

You'll need a using directive in your file to make this work:

using System.Linq;

Note that these don't use strings to express predicates and projects - they use delegates, usually created from lambda expressions as above.

If lambda expressions and LINQ are new to you, I would suggest you get a book covering LINQ first, such as LINQ in Action, Pro LINQ, C# 4 in a Nutshell or my own C# in Depth. You certainly can learn LINQ just from web tutorials, but I think it's such an important technology, it's worth taking the time to learn it thoroughly.

like image 184
Jon Skeet Avatar answered Oct 28 '22 02:10

Jon Skeet


you can also try

var query = from p in list
            where p.Age > 18
            select p;
like image 9
anishMarokey Avatar answered Oct 28 '22 02:10

anishMarokey