Home > database >  I have a String List with 10 elements inside. I need to randomly add 3 elements from the 10 into a W
I have a String List with 10 elements inside. I need to randomly add 3 elements from the 10 into a W

Time:11-20

    List<string> topLevel = new List<string>();
            

            topLevel.Add("000");
            topLevel.Add("100");
            topLevel.Add("200");
            topLevel.Add("300");
            topLevel.Add("400");
            topLevel.Add("500");
            topLevel.Add("600");
            topLevel.Add("700");
            topLevel.Add("800");
            topLevel.Add("900");

I tried

  var random=  topLevel.Distinct().OrderBy(x => Guid.NewGuid()).Take(3);
            lst2.Items.AddRange(random.ToArray());

But I get an 'AddRange' as underlined error and I do not know how to fix it

CodePudding user response:

Example:

    // Initial list source of values
    // This MUST be an observable collection
    private readonly ObservableCollection<string> lst2Source
        = new ObservableCollection<string>() { "1", "2" };

    // Immutable list of adding values
    private readonly ReadOnlyCollection<string> topLevel
        = Array.AsReadOnly("000 100 200 300 400 500 600 700 800 900".Split());

    public SomeWindow()
    {
        InitializeComponent();

        // Source is assigned once after XAML initialization
        lst2.ItemsSource = lst2Source;
    }

    private readonly Random random = new Random();
    private void AddRandom(int count)
    {
        topLevel
            .OrderBy(_ => random.Next())
            .Take(count)
            .ToList()
            .ForEach(level => lst2Source.Add(level)); // Elements are added not to the UI element, but to the value source
    }

it just prints 1 and 2 into my listbox

that i cannot lst2.items.clear();

"1" and "2" are the initial list values for the example. If they are not needed then remove them.
To add random elements, call the AddRandom(...) method.
To clear the collection, call lst2Source.Clear().

  • Related