JesseBuesking
JesseBuesking

Reputation: 6586

C# Dataset column removal using LINQ

I have a dataset with several columns, and all I want to do is remove all columns but those that I have in a List.

So, for example, the dataset has columns "ColA", "ColB", and "ColC". My list contains 1 item, the string "ColB". What I want to do is either remove "ColA" and "ColC", or say to only keep "ColB".

Is it possible to pull this off with LINQ, or even in general? I'm not sure how my dynamically generated list of strings could kill out columns on the original dataset.

Upvotes: 2

Views: 2065

Answers (2)

dasblinkenlight
dasblinkenlight

Reputation: 151

Performing "classic" projection requires compiler support

var res = myList.Select(d => new {d.ColB});

(the code above creates an anonymous class with a single property called ColB)

However, if execution speed is not overly important to you, it is possible to use ExpandoObject instead of a compiler-generated class, like this:

var columnList = new[] {"ColB"};
var res = myList.Select(d => Project(d, columnList));
...
static ExpandoObject Project(MyDataObject d, string[] columns) {
    var res = new ExpandoObject();
    // Using reflection here is a much better solution
    if (Array.IndexOf(columns, "ColA") >= 0) res.ColA = d.ColA;
    if (Array.IndexOf(columns, "ColB") >= 0) res.ColB = d.ColB;
    if (Array.IndexOf(columns, "ColC") >= 0) res.ColC = d.ColC;
    return res;
}

Upvotes: 0

s_nair
s_nair

Reputation: 812

var columnsFromTable = dt.Columns;// get all your column here
var columnsFromCollection = new string[] { "ColB" };//column to remove

Array.ForEach(columnsFromCollection,col=>
dt.Columns.Remove(col));

Upvotes: 1

Related Questions