76

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.

Zachary Dow
  • 1,897
  • 21
  • 36
MAC
  • 6,277
  • 19
  • 66
  • 111

5 Answers5

193

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

you can also try

var query = from p in list
            where p.Age > 18
            select p;
anishMarokey
  • 11,279
  • 2
  • 34
  • 47
6

Try this:

using System.Data.Linq;
var result = from i in list
             where i.age > 45
             select i;

Using lambda expression please use this Statement:

var result = list.where(i => i.age > 45);
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Hemant Kumar
  • 4,593
  • 9
  • 56
  • 95
4

Generic List<T> have the Where<T>(Func<T, Boolean>) extension method that can be used to filter data.

In your case with a row array:

var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));

If you are using DataRowCollection, you need to cast it first.

var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));
Zack
  • 2,789
  • 33
  • 60
Danil
  • 1,883
  • 1
  • 21
  • 22
1

I have used a script but to make a join, maybe I can help you

string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());
Luiz Pampu
  • 11
  • 1