简体   繁体   中英

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.

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));

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM