ID Name Value
......................
1 aa 123
2 bb 123
3 cd 123
Wanted to remove column "value" which has all the row values equal to 123 from Dataset using linq
ID Name Value
......................
1 aa 123
2 bb 123
3 cd 123
Wanted to remove column "value" which has all the row values equal to 123 from Dataset using linq
If you want to delet the whole column if all values are the same use Enumerable.All
, for example in:
foreach(DataTable dt in ds.Tables)
{
if(dt.Rows.Count > 0 && dt.Columns.Contains("Value") && dt.Columns["Value"].DataType == typeof(int))
{
int firstValue = dt.Rows[0].Field<int>("Value");
if(dt.AsEnumerable().Skip(1).All(r => r.Field<int>("Value") == firstValue))
{
dt.Columns.Remove("Value");
}
}
}
Update: "wanted to find and delete the column were all the values are same in that column."
Then you just have to generalize above code:
foreach (DataTable dt in ds.Tables)
{
List<DataColumn> columnsToDelete = new List<DataColumn>();
foreach (DataColumn col in dt.Columns)
{
object first = dt.Rows[0][col];
if (dt.AsEnumerable().Skip(1).All(r => r[col].Equals(first)))
{
columnsToDelete.Add(col);
}
}
foreach (DataColumn colToRemove in columnsToDelete)
dt.Columns.Remove(colToRemove);
}
Here return in list of datarow
ds.Tables["tableName"].AsEnumerable().Where(g => g.Field<Int32>("Value") != 123).ToList<DataRow>();
Worked with the solution given by SLaks https://stackoverflow.com/a/1766950/848286
foreach (var column in ds.Tables[0].Columns.Cast<DataColumn>().ToArray())
{
if (ds.Tables[0].AsEnumerable().All(dr => dr.IsNull(column)))
{
ds.Tables[0].Columns.Remove(column);
}
}