how to compare a string column value in a LINQ que

2019-09-06 13:34发布

问题:

I need to retrieve a set of "TOP n" number of rows from a DataTable where the table rows are Ordered By "Column X", but only if value of "Column X" for a row is greater than a provided comparison value. This is what I have so far:

EnumerableRowCollection query = from history in dt.AsEnumerable()
                                where history.Field<string>("Column X") > "Value-To-Compare")
                                orderby history.Field("Column X")
                                select history;

But I keep on getting "Operator '>' cannot be applied to operands of type 'string' and 'string'"

Any Thoughts?

fuzzlog

回答1:

Will this work?

EnumerableRowCollection query = from history in dt.AsEnumerable()
                                where String.Compare(history.Field<string>("Column X"), "Value-To-Compare") > 0
                                orderby history.Field("Column X")
                                select history;


回答2:

Ian, that did the trick, Thanks.

Sorry for answering my question after you gave the solution, but I needed to enhance your answer so it matches 100% the original request.

...retrieve a set of "TOP n" number of rows...

The complete answer should look like this:

EnumerableRowCollection query = (
                                  from history in dt.AsEnumerable() 
                                  where String.Compare(history.Field<string>("Column X"), "Value-To-Compare") > 0 
                                  orderby history.Field("Column X") 
                                  select history
                                ).Take(n); 

Where "n" is the number of rows specified in "Top n"

Thanks again,

fuzzlog



标签: linq-to-sql