0

I'm querying a list of objects.

Some of those objects have a propertie startTime which may have null values.

For those cases i want to generate a random number. For other cases I want to get the different between current time and the respective Item StartTime

var data =  List.Select(e => new myCustomItem 
                             {
                                Item = e,
                                TimeDistance = (e.StartTime.HasValue ? (e.StartTime.Value - DateTime.Now).TotalMinutes : RandomNumber(-5000, 5000))
                             })
                .OrderBy(e => e.TimeDistance)
                .ToList();

This is the function that should be called at every results that has a null value.

private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

The problem is that all the results are reciving the same value.

For others that have a startDate assigned (not null) it is performing the calc.

Lothre1
  • 3,523
  • 7
  • 43
  • 64

1 Answers1

1

If I understood you correctly, you want something like this:

var random = new Random();
var data =  List.Select(e => new myCustomItem 
{
    Item = e , 
    TimeDistance = (e.StartTime.HasValue ? 
         (e.StartTime.Value - DateTime.Now).TotalMinutes :
          Enumerable.Range(-5, 5).OrderBy(i => random.NextDouble()).ToList().First()) 
}).OrderBy(e => e.TimeDistance).ToList();
Alex
  • 8,827
  • 3
  • 42
  • 58
  • 1
    Are you serious? Build and order a list of 10000 items with 10000 random numbers for each iteration? – Gert Arnold Feb 20 '13 at 11:14
  • Thank you voo, all i had to do was to replace my call to the custom method RandomNumber() by a call refering the method of a previous instanteated new Random Object. Like you have done in the first line. (btw, i just need to order the list at the end of the random process) :) – Lothre1 Feb 20 '13 at 11:14
  • You are welcome. And Gert is right, linq random alternative is a bad idea for large Ranges. But you can use it for small ones – Alex Feb 20 '13 at 11:18