Wednesday, June 25, 2008

Filling a list of classes with random values using linq

Filling a list of classes (10 for this example) with random values using linq. Enumerable.Range(0, 10) - This means give me a list from 1 to 10
Enumerable.Range(0, 10).Select
(
  j =>
- This means you are going to select every j in the list Enumerable created
Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
- For every J in the list, create a new junkItem
Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
  }
)
- This is the new way to set a property in 3.5. I could just use a constructor, and probably should but this was just thrown together.
Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
  }
)
- Once again, I am using Enumerable to create a list. This one will have 1 item. I will use Select to go through the list.For every i in the list, test (this is the Random object) will create a random number and give me a list of random numbers the size of the Enumerable.Range list.
Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
 }
).ToList()
- I just want one random number, so I will get the number t the first index. Although with this, I only have on number in the list anyhow. The property of the current JunkItemB will be set to this. Once this is done, it will be repeated 9 more times.
Enumerable.Range(0, 10).Select
(
  j => new JunkItemB()
  {
    SomeNumber = Enumerable.Range(0, 1).Select
    (
      i => randomGenerator.Next()
    ).ElementAt(0)
 }
).ToList()
- Now that I have my list of 10 JunkItemBs, I will create a new list and from it giving me 10 JunkItemBs with preset SomeNumber properties. Now that I look at this again (This is taken from notes I had somewhere else) I could have just used Random to get a number instead of Enumerator. Yay for over complicating things. Also my explanation of Select is a bit misleading for those who haven't used lambda expressions. I'll explain further in my next post. Namespaces: using System; using System.Collections.Generic; using System.Linq; using System.Text;

No comments: