gpt4 book ai didi

c# - 如何在 LINQ 中随机使用 First()?

转载 作者:太空狗 更新时间:2023-10-29 22:04:08 25 4
gpt4 key购买 nike

在这样的列表中:

var colors = new List<string>{"green", "red", "blue", "black","purple"};

我可以这样得到第一个值:

var color = colors.First(c => c.StartsWidth("b")); //This will return the string with "blue"

Bot 如果我想要一个匹配条件的随机值,我该怎么做?例如这样的事情:

Debug.log(colors.RandomFirst(c => c.StartsWidth("b"))) // Prints out black
Debug.log(colors.RandomFirst(c => c.StartsWidth("b"))) // Prints out black
Debug.log(colors.RandomFirst(c => c.StartsWidth("b"))) // Prints out blue
Debug.log(colors.RandomFirst(c => c.StartsWidth("b"))) // Prints out black

如果列表中有多个条目符合条件,我想随机拉出其中一个。它(我需要它)是一个内联解决方案。谢谢。

最佳答案

然后随机排序:

var rnd = new Random();
var color = colors.Where(c => c.StartsWith("b"))
.OrderBy(x => rnd.Next())
.First();

上面的代码为每个元素生成一个随机数,并根据该数字对结果进行排序。

如果您只有 2 个元素符合您的条件,您可能不会注意到随机结果。但是您可以尝试下面的示例(使用下面的扩展方法):

var colors = Enumerable.Range(0, 100).Select(i => "b" + i);

var rnd = new Random();

for (int i = 0; i < 5; i++)
{
Console.WriteLine(colors.RandomFirst(x => x.StartsWith("b"), rnd));
}

输出:

b23
b73
b27
b11
b8

您可以从这个名为 RandomFirst 的方法中创建一个扩展方法:

public static class MyExtensions
{
public static T RandomFirst<T>(this IEnumerable<T> source, Func<T, bool> predicate,
Random rnd)
{
return source.Where(predicate).OrderBy(i => rnd.Next()).First();
}
}

用法:

var rnd = new Random();
var color1 = colors.RandomFirst(x => x.StartsWith("b"), rnd);
var color2 = colors.RandomFirst(x => x.StartsWith("b"), rnd);
var color3 = colors.RandomFirst(x => x.StartsWith("b"), rnd);

优化:

如果你担心性能,你可以尝试这个优化的方法(将大列表的时间减少一半):

public static T RandomFirstOptimized<T>(this IEnumerable<T> source, 
Func<T, bool> predicate, Random rnd)
{
var matching = source.Where(predicate);

int matchCount = matching.Count();
if (matchCount == 0)
matching.First(); // force the exception;

return matching.ElementAt(rnd.Next(0, matchCount));
}

关于c# - 如何在 LINQ 中随机使用 First()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38606521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com