Alan2
Alan2

Reputation: 24602

How can I modify my code to get data from an array of objects in C#?

I have the following class:

public partial class Content
{

    public int ContentId { get; set; }
    public int ContentTypeId { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public System.DateTime ModifiedDate { get; set; }
    public virtual byte[] Version { get; set; }

    public int SubjectId { get; set; }
    public virtual Subject Subject { get; set; }

}

and the following code:

var myData = new[] {
   "Content 1",
   "Content 2",
   "Content 3" 
};

var contents = myData.Select(e => new Content
{
   Title = e,
   Text = "xx",
   ModifiedDate = DateTime.Now
}

How can I modify this so I can specify both the "Title" and some small sample "Text" in the myData array. I was thinking about using an array of objects but I am not quite sure how to set this up.

Upvotes: 3

Views: 75

Answers (2)

Stay Foolish
Stay Foolish

Reputation: 3756

How about you use Tuple?

        var myDatas = new[]
        {
            new Tuple<string, string, DateTime>("Title", "Example", DateTime.Now),
            new Tuple<string, string, DateTime>("Title2", "Example", DateTime.Now.AddDays(-1)),
            new Tuple<string, string, DateTime>("Title3", "Example", DateTime.Now.AddDays(1))
        };

        var contents = myDatas.Select(e => new Content
        {
            Title = e.Item1,
            Text = e.Item2,
            ModifiedDate = DateTime.Now
        });

Upvotes: 1

Vasanth
Vasanth

Reputation: 1710

Here is the syntax for that:

var myData = new List<Content>
            {
              new Content{Title = "Content 1", Text = "xx", ModifiedDate = DateTime.Now},
              new Content{Title = "Content 2", Text = "AB", ModifiedDate = DateTime.Now},
              new Content{Title = "Content 3", Text = "CC", ModifiedDate = DateTime.Now}
            };

Upvotes: 1

Related Questions