Rick
Rick

Reputation: 5

Finding if value is between two columns in data table

For the past week I have been searching for an answer to this problem I am having and I cannot seem to find the answer.

I have written a program to run a raffle for an online game I play. The problem I have is that I need to remove duplicates from the drawing of the main prizes (new requirement).

What I have now the database gets loaded into a DataTable and then I generate a random number and then I need to find where that random number falls between two columns in the DataTable, TicketNumberStart and TicketNumberEnd. Here is what I am using for my LINQ right now.

var winner = from jnkDt in dt.AsEnumerable()
    where
    jnkDt.Field<int>("TicketNumberStart") > rndNumber &&
    jnkDt.Field<int>("TicketNumberEnd") < rndNumber
    select new
    {
        name = jnkDt.Field<string>("BuyerName")
    };
    foreach (var jnk in winner)
        tmpName = jnk.name.ToString();

The problem I am running into is that this returns a blank string no matter what the rndNumber is.

Upvotes: 0

Views: 561

Answers (1)

D Stanley
D Stanley

Reputation: 152521

I'm assuming that TicketNumberEnd is more than TicketNumberStart, in which case your condition will never be true. I suspect you need to flip the comparisons:

var winner = from jnkDt in dt.AsEnumerable()
    where
    jnkDt.Field<int>("TicketNumberStart") <= rndNumber &&
    jnkDt.Field<int>("TicketNumberEnd") >= rndNumber
....

OR

var winner = from jnkDt in dt.AsEnumerable()
    where
    rndNumber >= jnkDt.Field<int>("TicketNumberStart") &&
    rndNumber <= jnkDt.Field<int>("TicketNumberEnd") 

Upvotes: 2

Related Questions