为某些满足某些条件的对象分配随机排列

时间:2017-03-10 14:27:28

标签: c#

我有一个对象列表List<People> person= new List<People>();,每个对象(person)都有一些属性(例如agerank等)。

我希望找到年龄相同的person,并为其rank分配随机排列。

例如:person[0].age=20; person[1].age=22; person[2].age=22; person[3].age=20; person[4].age=20;

因此,可行的情况可以是

person[0].rank=3; person[1].rank=1; person[2].rank=2; person[3].rank=2; person[4].rank=1;

3 个答案:

答案 0 :(得分:0)

var personsByAge = persons.GroupBy(person => person.age); 
foreach(var personAgeGroup in personsByAge) 
{
    var counter = 1;
    foreach(var person in personAgeGroup.Shuffle())
    {
        person.rank = counter;
        counter++;
    }
}

//Shuffling

public static class EnumerableExtensions
{
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
    {
        return source.Shuffle(new Random());
    }

    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (rng == null) throw new ArgumentNullException("rng");
        return source.ShuffleIterator(rng);
    }

    private static IEnumerable<T> ShuffleIterator<T>(
    this IEnumerable<T> source, Random rng)
    {
        var buffer = source.ToList();
        for (int i = 0; i < buffer.Count; i++)
        {
            int j = rng.Next(i, buffer.Count);
            yield return buffer[j];
            buffer[j] = buffer[i];
        }
    }
}

Credit to LukeH for the shuffle code.

答案 1 :(得分:0)

假设我们有一个清单

@ExceptionHandler(MaxUploadSizeExceededException.class)
    public String handleError(MaxUploadSizeExceededException e, RedirectAttributes redirectAttributes) {
        .......
    }

获取不同年龄并为分享此年龄的每个人分配特定的等级值

List<People> person = new List<People>();

答案 2 :(得分:0)

这是另一种方法

void Main()
{
    IEnumerable<Person> people = new Person[] {
        new Person(1,20,"Bob"),
        new Person(1,22, "John"),
        new Person(1,22, "Paul"),
        new Person(1,20, "Kim"),
        new Person(1,20, "Justin")
    };

    List<Person> rankedPeople = new List<Person>();

    // just used for some sorting
    Random r = new Random((int)DateTime.Now.Ticks); 

    // Group by age and sort them randomly 
    foreach (var groupedPeople in people.GroupBy(p => p.Age) )
    {
        // Copy the persons from original list to a new one, at the sametime updating rank. 
        rankedPeople.AddRange(  groupedPeople.OrderBy(gp => r.Next()).Select( (val,index)  =>  new Person(index,val.Age, val.Name) ) );  
    }

    rankedPeople.ForEach(p => System.Console.WriteLine(p.ToString()));
}


public class Person
{
    public Person(int rank, int age, string name)
    {
        this.Rank = rank;
        this.Age = age;
        this.Name = name;
    }
    public int Rank { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return string.Format($"{Rank} {Age} {Name}");
    }
}