-4

I am trying to get biggest number in a data table.

int tempVariable;
int highestNumber = dt1.Tables[0].AsEnumerable()
                                .Where(x => int.TryParse(x.Field<string>("dataComponent"), out tempVariable))
                                .Max(m => int.Parse(m.Field<string>("dataComponent")));

I have tried like above, but it is throwing Sequence contains no elements error. What can I do to fix it?

mason
  • 31,774
  • 10
  • 77
  • 121
xyz
  • 61
  • 7
  • 4
    can you please share a sample of the _actual_ content of your datatable? _could it be_ that none of your fields contains anything that can be parsed as int? i mean - at least that's what the error message tells you. – Franz Gleichmann Jun 16 '21 at 13:51
  • SampleList12tbxName something like this bro . i want to get 12 from it – xyz Jun 16 '21 at 13:52
  • within number can be 1,2,3,4....... 99 – xyz Jun 16 '21 at 13:53
  • 1
    Have a look at this: https://stackoverflow.com/questions/1324199/sequence-contains-no-elements and read up on [this](https://blogs.msmvps.com/kevinmcneish/2009/12/17/fixing-linq-error-sequence-contains-no-elements/) to learn how to analyze what is causing your Linq exception. – DeMaki Jun 16 '21 at 13:53
  • 3
    `int.Parse` expects a string that is parseable as it is, e.g "12" or "-1234". You need to extract the numeric part of the string before calling it. – René Vogt Jun 16 '21 at 13:56
  • "SampleList12tbxName" is ***not*** a valid representation of an integer...... also: please provide additional information by ***editing*** your question. – Franz Gleichmann Jun 16 '21 at 13:57

2 Answers2

0

This seems very similar to your code and it works (prints out 123).

var strings = new[] { "1", "abc", "12", "123" };
var highest = strings.Where(x => int.TryParse(x, out var _)).Max(m => int.Parse(m));
Console.WriteLine(highest);

Can you add information to your question so we can reproduce your error?

Hans Kilian
  • 18,948
  • 1
  • 26
  • 35
  • ex:- ab45vb ,ab43vb here i need to get 45 bro – xyz Jun 16 '21 at 13:59
  • this basically _is_ the same code. the cause of the problem is that the input data doesn't represent valid integers, but needs to be parsed first. – Franz Gleichmann Jun 16 '21 at 14:00
  • From the literal `ab45vb` the function `int.TryParse` will always return false so the where statement will filter out that row... – Cleptus Jun 16 '21 at 14:04
0

Hi for this question I have used regex to get the string . then I used the same method I posted in the question .

xyz
  • 61
  • 7