0
foreach (DataRow row in dt.Rows ) 
        avlCols.Add(row.ItemArray[0].ToString().Trim());
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
Geek
  • 195
  • 1
  • 1
  • 9

3 Answers3

4

There's nothing wrong with that code.

If you're looking for a LINQ one-liner to solve the problem, you could try:

// I added ToList since it looks like your original used a list.
// If you only need IEnumerable, then you can leave off that call.
var avlCols = dt.AsEnumerable()
                .Select(r => r.Field<string>(0).Trim()).ToList();

Or (if you simply need to add those items to an existing list):

avlCols.AddRange(dt.AsEnumerable()
                   .Select(r => r.Field<string>(0).Trim()));

For both of those options, you have to make sure you add a reference to the System.Data.DataSetExtensions assembly as well as have access to the System.Linq namespace.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

A couple of suggestions:

  • use good variable names
  • use the column name instead of the index
  • use LINQ

An example:

var names = from personRow in personTable.AsEnumerable()
            select personRow["name"].ToString().Trim();
Jordão
  • 55,340
  • 13
  • 112
  • 144
  • If you happen to know the index (perhaps you only have one column) it's faster to use the index instead of forcing the DataRow to look up the index from the name once per row. – Joel Mueller Jun 09 '11 at 20:34
  • Yes it is faster. But until it's a proven _bottleneck_, I'd favor readability and maintainability. And I don't think it would be a bottleneck in a system that (probably) also employs a database. – Jordão Jun 10 '11 at 00:27
0

You may be able to get away with:

var avlCols = from row in dt.Rows select row.ItemArray[0].ToString().Trim();
Gabe
  • 84,912
  • 12
  • 139
  • 238