0

I need to get a specific column header name based on value.

For ex: I am using the below query to get list of column headers and it works fine and on top of this can I get column names which has specific name like Department alone.

LINQ

string[] columnNames = dt.Columns.Cast<DataColumn>()
                         .Select(x => x.ColumnName)
                         .ToArray();

How can I add contains or exists to this query to get specific columns.

5
  • 1
    You mean like adding .Where(x => x == "Department")? Commented Dec 26, 2017 at 14:46
  • @DavidG x is DataColumn. How is that possible? Probably you mean .Where(x => x.ColumnName == "Name"). Check my answer. Commented Dec 26, 2017 at 15:06
  • 1
    @S.Akbari Not if you put that line after the Select. I didn't answer this question because it's unclear and rather pointless to select a single string from a list of strings when you already have the string. I wish other people had thought the same... Commented Dec 26, 2017 at 15:07
  • @DavidG Yes by putting Where after Select it works and I also have pointed this. I thought you said replace Select with Where. Commented Dec 26, 2017 at 15:11
  • @S.Akbari And nothing to say about the second part of my comment? Commented Dec 26, 2017 at 15:14

4 Answers 4

2

Simply add a filter, like this:

string[] columnNames = dt.Columns.Cast<DataColumn>()
                             .Select(x => x.ColumnName)
                             .Where(x => x == "Department")
                             .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

2
List<string> containsKeys = new List<string>();
containsKeys.Add("SomeWildCard");

DataTable dt = new DataTable();
string[] columnNames = dt.Columns.Cast<DataColumn>()
                             .Select(x => x.ColumnName)
                             .ToArray().Where(t => containsKeys.Contains(t)).ToArray();

Comments

1

You can either select then filter the result:

.Select(x => x.ColumnName).Where(c => c == "Department")

Or first filter then select:

.Where(x => x.ColumnName == "Department").Select(c => c.ColumnName)

Comments

1

Columns property is of type DataColumnCollection, which has an indexer public DataColumn this[string name] to get DataColumn by name:

DataColumn dc = dt.Columns["Department"];

to get multiple columns by name use Select() with indexer:

List<string> names = new List<string> { "Department", "Something" };
DataColumn[] columns = names.Select(name => dt.Columns[name]).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.