Search code examples
c#icollection

Add items to ICollection


I defined an ICollection as

 public virtual ICollection<Attempt> Attempts { get; set; }

And Attempt is defined as

 public class Attempt
 {
     public Guid Id { get; set; }
     public string AttemptsMetaData { get; set; }
     public DateTime Time { get; set; }
     public bool Answered { get; set; }
     public DateTime Disconnected { get; set; }
 }

Now I want to pass ICollection to a method.

public void AddTask(ICollection<Attempt> attempts)
{
    // Do something to the item in attempts.
} 

Now I have to create a sample data to this collection. I am not sure how. The code below maybe wrong. What I thought was

        // test data
        Guid id = new Guid();
        string attempt = "test";
        DateTime dt = DateTime.Now.AddDays(-1);
        bool answered = true;
        DateTime disconnected = DateTime.Now;
        ICollection <Attempt> attempts= new List<Attempt>();
        // try to add sample data to the list

Solution

  • List<Attempt> attempts= new List<Attempt>();
    //Create a Instance of Attempt
    Attempt objAtt = new Attempt();
    Guid id = new Guid();
    objtAtt.Id =id;
    objtAtt.Time = DateTime.Now;
    objAtt.AttemptsMetaData ="test";
    objAtt.Answered = true;
    objAtt.Disconnected = DateTime.Now;
    attempts.Add(objAtt);
    

    Here you pass to method,

    AddTask(attempts);
    

    Your method like this,

    public void AddTask(List<Attempt> attempts)
    {
    
    }