如何在LINQ查询中使用随机函数? [英] How to use random function in LINQ Query?
本文介绍了如何在LINQ查询中使用随机函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尊敬的先生,
如何在LINQ中使用随机函数?
我有50条记录,现在将其自动更改为随机顺序....
如何解决此问题回复我.....
Dear sir,
How to use Random function in LINQ?
I have 50 records, now change this automatically into random order....
How to solve this Reply me.....
推荐答案
一种选择是使用从IComparer<T>
类继承的Comparer
类,如下所示:
One option is to use aComparer
class inherited fromIComparer<T>
class as shown below:
void Main()
{
List<person> persons = new List<person>(){
new Person("A","M"),
new Person("B","N"),
new Person("C","O"),
new Person("D","P"),
new Person("E","Q"),
new Person("F","R"),
new Person("G","S"),
new Person("H","T")
};
var query = persons.OrderBy(p => p,new RandomComparer());
}
//query output
//Name Address
//A M
//C O
//D P
//F R
//E Q
//B N
//H T
//G S
public class Person {
public string Name {get; set;}
public string Address {get; set;}
public Person(string name, string address){
Name = name;
Address = address;
}
}
public class RandomComparer : IComparer<person> {
Random random = new Random();
public int Compare(Person first, Person second){
return random.Next(-1,2);
}
}
请参阅此链接..
http://stackoverflow.com/questions/648196/random-row-from-linq- to-sql [^ ]
http://netpl.blogspot.com/2008/07/generating-random- sequence-with-linq.html [ ^ ]
http://blog.wujitouch.com/post/LINQ-Select- a-random-object-or-entity.aspx [ ^ ]
Please refer this link..
http://stackoverflow.com/questions/648196/random-row-from-linq-to-sql[^]
http://netpl.blogspot.com/2008/07/generating-random-sequences-with-linq.html[^]
http://blog.wujitouch.com/post/LINQ-Select-a-random-object-or-entity.aspx[^]
我刚刚发布了一些代码,其中包括用于向LINQ添加随机功能的几种扩展方法,包括random选择和改组.
使用随机操作扩展LINQ [
I''ve just posted some code that includes several extension methods for adding random functionality to LINQ, include random selection and shuffling.
Extending LINQ with Random Operations[^]
这篇关于如何在LINQ查询中使用随机函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文