0

It it possible to add 500 objects by for loop into an array using C#?

    public class DataBase
    {
        public Items[] GetItems()
        {
            return new Items[] {
                new Items (1, "item1" ),
                new Items (2, "item2"),
                new Items (3, "item3")};

                // for here?
        }

    }

The items should be unique :) also first value in Items object is uint, so it should be converted somehow?

5
  • are u using a model for adding? or u just simple want to add using pattern above? Commented Jan 2, 2017 at 8:57
  • 2
    You can give this a try return Enumerable.Range(1, 500).Select(x => new Items (x, "item" + x )).ToArray(); Commented Jan 2, 2017 at 8:58
  • 1
    @Satpal .ToArray(); at end of it :P Commented Jan 2, 2017 at 8:59
  • @Satpal should it be .ToArray after => new Items (...) ? 1 more thing! "x" or first value in Items object is uint, how can I convert it to uint dynamically ? Commented Jan 2, 2017 at 9:01
  • @bodley, new Items(((uint)x), "item" + x) Commented Jan 2, 2017 at 9:05

2 Answers 2

7

Enumerable.Range:

public class DataBase
{
    public Items[] GetItems()
    {
        return Enumerable.Range(1,500).Select(o => new Items ((uint)o, "item" + o)).ToArray();     
    }
}

Reference:

public static IEnumerable<int> Range(
    int start,
    int count
)
Sign up to request clarification or add additional context in comments.

3 Comments

what with uint conversion?
@bodley just cast (uint)o
perfect, that is what I need! Thank you so much! :)
2

You can use Enumerable.Range and type case x to unit

return Enumerable.Range(1, 500).Select(x => new Items((uint)x, "item" + x)).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.