简体   繁体   English

在数组中查找多个数字

[英]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?如何检查 array2 的数字是否包含在 array1 中并仅从现有列表中随机选择一个数字?

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.在示例中,检查结果为 [4, 10],因为 3 和 8 不在 array2 中,然后我想随机选择 4 或 10,它们包含在 array1 和 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:您想使用 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()现在生成一个介于 0 和 intersect.Count() 之间的随机数

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

Pick element at position randomIndex在 position randomIndex 处选取元素

var randomPick = intersect.ElementAt(randomIndex);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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