Nate Pet
Nate Pet

Reputation: 46322

Add items to list from linq var

I have the following query:

    public class CheckItems
    {
        public String Description { get; set; }
        public String ActualDate { get; set; }
        public String TargetDate { get; set; }
        public String Value { get; set; }
    }



   List<CheckItems>  vendlist = new List<CheckItems>();

   var vnlist = (from up in spcall
               where up.Caption == "Contacted"
                      select new CheckItems
                      {
                          Description = up.Caption,
                          TargetDate = string.Format("{0:MM/dd/yyyy}", up.TargetDate),
                          ActualDate = string.Format("{0:MM/dd/yyyy}", up.ActualDate),
                          Value = up.Value
                      }).ToList();

// Next, when I try to add vnlist to vendlist, I get an error as I cannot add this to the list I get and error saying I have some invalid arguments

         vendlist.Add(vnlist);

Upvotes: 25

Views: 96838

Answers (4)

Talha Imam
Talha Imam

Reputation: 1116

Here's one simple way to do this:

List<CheckItems>  vendlist = new List<CheckItems>();

var vnlist =    from up in spcall
                where up.Caption == "Contacted"
                select new
                  {
                      up.Caption,
                      up.TargetDate,
                      up.ActualDate,
                      up.Value
                  };

foreach (var item in vnlist)
            {
                CheckItems temp = new CheckItems();
                temp.Description = item.Caption;
                temp.TargetDate = string.Format("{0:MM/dd/yyyy}", item.TargetDate);
                temp.ActualDate = string.Format("{0:MM/dd/yyyy}", item.ActualDate);
                temp.Value = item.Value;

                vendlist.Add(temp);
            }

Upvotes: 1

Samich
Samich

Reputation: 30185

If you need to add any IEnumerable collection of elements to the list you need to use AddRange.

vendlist.AddRange(vnlist);

Upvotes: 38

CrazyDart
CrazyDart

Reputation: 3801

Or combine them...

vendlist.AddRange((from up in spcall
               where up.Caption == "Contacted"
                      select new CheckItems
                      {
                          Description = up.Caption,
                          TargetDate = string.Format("{0:MM/dd/yyyy}", up.TargetDate),
                          ActualDate = string.Format("{0:MM/dd/yyyy}", up.ActualDate),
                          Value = up.Value
                      }).ToList());

Upvotes: 5

Michel Keijzers
Michel Keijzers

Reputation: 15377

I think you try to add a complete list instead of a single CheckItems instance. I don't have a C# compiler here but maybe AddRange instead of Add works:

vendlist.AddRange(vnlist);

Upvotes: 3

Related Questions