B
B
baimkin2018-06-21 11:33:48
C++ / C#
baimkin, 2018-06-21 11:33:48

Linq to DataTable how to get row with minimum value in column?

I'm trying to get a row with a minimum value in a column, in a column of this kind of data:
10914.76 10970
i.e.
there are both voids and null

IEnumerable<DataRow> results = from myRow in dt.AsEnumerable()
                              orderby double.Parse("Цена") where !String.IsNullOrWhiteSpace("Цена")
                              select myRow;
DataRow row = results.FirstOrDefault();

but I get an error System.FormatException: "The input string was not in the correct format."
I also tried this:
where ("Price") != null && ("Price") != ""
if I remove double.Parse , I get data from the first row in the table

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Nemiro, 2018-06-21
@baimkin

Database-level nulls need to be checked with DBNull.Value . If prices are stored as strings, be aware that different cultures may use different decimal separators. It is better to store the data immediately as a number so that there are no problems with format conversion, and the code runs faster. "Price" in the provided code is just a string containing the word "Price". If it is a field name, then it should be referred to as myRow .

from myRow in dt.AsEnumerable()
where myRow["Цена"] != DBNull.Value
orderby double.Parse(myRow["Цена"])
select myRow;

D
DENIS Kokorev, 2018-06-21
@shmaroder

Try it like this:

IEnumerable<DataRow> results = from myRow in dv.Table.AsEnumerable()
                                           orderby double.Parse(myRow["Цена"].ToString())
                                           where myRow["Цена"]!=null && myRow["Цена"]!=""
                                           select myRow;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question