2017-05-08 58 views
0

我正在使用以下代碼來生成隨機顏色。將隨機生成的值鏈接到列表對象

static Color[] colors = { Color.Red, Color.Green, Color.Yellow}; 
static Color GetRandomColor() 
{ 
    var random = new Random(); 
    return colors[random.Next(colors.Length)]; 
} 

現在我需要關聯到用戶的列表:

 List<Utente> ListaUtente = new List<Utente>(); 
     ListaUtente.Add(new Utente(22, "Pedro", 555444333, "[email protected]")); 
     ListaUtente.Add(new Utente(22, "Lucas", 555444333, "[email protected]")); 
     ListaUtente.Add(new Utente(22, "Rodrigo", 555444333, "[email protected]")); 
     ListaUtente.Add(new Utente(22, "Gaspar", 555444333, "[email protected]")); 
     ListaUtente.Add(new Utente(22, "Assis", 555444333, "[email protected]")); 

並在屏幕上一樣顯示出來:用戶1 - 紅, 用戶2 - 格林等

什麼最簡單的方法來做到這一點?我不知道如何連接這兩個代碼塊。只是爲了給你一些背景我在做一個醫院管理服務,我需要爲每個用戶分配一個緊急顏色。

+0

這是winforms,WPF,ASP.NET,控制檯......? –

+0

添加顏色屬性到'Utente'? –

+0

製作一個List >而不是'List '? –

回答

2
public class Person 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string Color { get; set; } 
} 
public class Colours 
{ 
    public string ColourName { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 

     List<Person> People = new List<Person>() 
     { 
      new Person { Id = 1, Name = "Dave" }, 
      new Person { Id = 2, Name = "Joe" }, 
      new Person { Id = 3, Name = "Stephen"}, 
      new Person { Id = 4, Name = "Sue" }, 
      new Person { Id = 5, Name = "Jemma" }, 
      new Person { Id = 6, Name = "Sharon" }, 
     }; 
     Dictionary<int, Colours> Colours = new Dictionary<int, Colours>() 
     { 
      { 1, new Colours { ColourName = "Color.Red" }}, 
      { 2, new Colours { ColourName = "Color.Green"}}, 
      { 3, new Colours { ColourName = "Color.Blue"}}, 
     }; 

     Random RandomNumber = new Random(); 

     int ListPostionToRemoveAt = RandomNumber.Next(1, People.Count); 
     int RandomColourPostion = RandomNumber.Next(1, Colours.Count); 

     Person p = People[ListPostionToRemoveAt]; 

     Colours ColourToAssign = Colours[RandomColourPostion] ; 
     p.Color = ColourToAssign.ColourName; 
     Console.Write("Persons Name: " + p.Name +" Persons Colour:"+ p.Color); 
     Console.ReadLine(); 
    } 
} 
+1

基本上使用字典來存儲您的顏色,因爲它可以將它們連接到一個更加平滑的用戶。你可以很容易地擴展它,添加一個foreach循環遍歷列表,刪除用過的元素/人員,以確保你不會重複。 如果您需要更多指導,請詢問。 –

+0

謝謝,現在就試試這個,稍後會給你反饋! – Dany4k

+0

所以從我的低估來看,這段代碼並不需要我發佈的前一段代碼正確嗎?還有你有人的地方,我把它換成「Utente」吧? – Dany4k