简体   繁体   中英

Find multiple numbers in array

I need to find multiple numbers contained in array, and randomly pick one. This is my code:

 var get = JsonConvert.DeserializeObject<List<int>>(json);
 var number = get.Where(r => r = 1).FirstOrDefault();

 if (number = 1)
 {
     //DO SOMETHING

 }

How do i randomly pick a number from an array list which is contained in the other array?

For example:

array1 = [1, 2, 4, 5, 6, 7, 9, 10]
array2 = [3, 4, 8, 10]

How do I check if numbers of array2 are contained inside array1 and randomly pick a number from the existing list only?

On the example, the check would give as result [4, 10] as 3 and 8 are not in array2, then I want to randomly pick either 4 or 10, which is contained inside the array1 and array2.

Those were just an example and not the actual numbers.

Try this:

        var randomValue = array1
            .Where(x => array2.Contains(x))
            .OrderBy(q => Guid.NewGuid())
            .FirstOrDefault();

You'd want to use set intersect:

int[] arr1 = new int[] { 1, 2, 4, 5, 6, 7, 9, 10 };
int[] arr2 = new int[] { 3, 4, 8, 10 };

var intersect = arr1.Intersect(arr2);
//intersect = {4, 10}

Now generate a random number between 0 and intersect.Count()

Random rand = new Random();
var randomIndex = rand.Next(intersect.Count());

Pick element at position randomIndex

var randomPick = intersect.ElementAt(randomIndex);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM