Home > Software design >  C# datatable linq receiving mode 3 this ushort variable "Mins"
C# datatable linq receiving mode 3 this ushort variable "Mins"

Time:03-16

I've written a linq command that makes the mins variable go three, but I'm getting an InvalidCastException. Does this command work without the System.Data.DataSetExtension.dll?

I can't add this reference because this is already exists but there is no this dll. Thanks

This is my code:

dataTable = dataTable.AsEnumerable()
                     .Where(x => x.Field<int>("Mins") % 3 == 0)
                     .CopyToDataTable();

CodePudding user response:

Let me clarify your requirement: You want filter the rows that the column Mins

  1. has only integer value
  2. is a multiply of 3.
        static DataTable GenerateTestTable(string[] nums)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Mins");
            foreach (string num in nums)
            {
                DataRow row = dt.NewRow();
                row[0] = num;
                dt.Rows.Add(row);
            }
            return dt;
        }

        static void Main(string[] args)
        {
            DataTable dt = GenerateTestTable(new string[] { "1", "3", ".3" });
            int n;
            dt = dt.AsEnumerable()
                   .Where(x => int.TryParse(x["Mins"].ToString(), out n)
                            && n % 3 == 0)
                   .CopyToDataTable();
            foreach (DataRow r in dt.Rows)
            {
                Console.WriteLine(r[0]);
            }
            //only outputs 3
            Console.ReadKey();
        }

Seems .Where(x => Convert.ToDouble(x["Mins"]) % 3 == 0) works too. But I still prefer checking int first, because I'm never confident of result of double % .

reference

C# testing to see if a string is an integer?

Field(DataRow, String)

  • Related