Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items to list from linq var

Tags:

c#

linq

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);
like image 660
Nate Pet Avatar asked Feb 09 '12 17:02

Nate Pet


4 Answers

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

vendlist.AddRange(vnlist);
like image 89
Samich Avatar answered Nov 16 '22 06:11

Samich


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());
like image 6
CrazyDart Avatar answered Nov 16 '22 05:11

CrazyDart


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);
like image 3
Michel Keijzers Avatar answered Nov 16 '22 06:11

Michel Keijzers


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);
            }
like image 1
Talha Imam Avatar answered Nov 16 '22 05:11

Talha Imam