Home > Back-end >  Except on Lists in c#
Except on Lists in c#

Time:12-28

I count months and years from a given date to the present date and from this list I have to subtract the months that were returned to me in the sql (linq) query. I try to use "Except" on the results, but gives me an error in the picture below

  var list = _ecpContext.Akceptacje_UnionAll_V
                   .Where(f => f.ADLogin == user)
                   .Select(f => new
                   {
                       Miesiac= f.Miesiac,  //month
                       Rok= f.Rok  // year
                   })
                   .ToList();

//-------------------------------------------------------------------

                DateTime employmentDate = _ecpContext.Ustawienia.FirstOrDefault(x => x.UstLogin == user).EmploymentDate;
                int employmentYear = employmentDate.Year;
                int employmentMonth = employmentDate.Month;

                DateTime now = DateTime.Now;
                int currentYear = now.Year;
                int currentMonth = now.Month;

                var newList = Array.Empty<object>().Select(x => new { Month = 1, Year = 1 }).ToList();

                for (var i = employmentYear; i <= currentYear; i  )
                {
                    for (var x = employmentMonth; x <= currentMonth; x  )
                    {
                        newList.Add(new { Month = x, Year = i });
                    }
                }

//-------------------------------------------------------------------

// i try
                IEnumerable<DatesOfShortages> listMissingDates = list.Except(newList);

 public class DatesOfShortages
    {
        public int Year { get; set; }
        public int Month { get; set; }
    }

new error

enter image description here

CodePudding user response:

The Except method is a method which produces the set difference of two sequences so you need to invoke it.

IEnumerable<DatesOfShortages> listMissingDates = newList.Except(list);

CodePudding user response:

You can't have one list A full of anonymous types, and another list B full of Tuples, and run a.Except(b) on them

Make a list of anonymous types instead of tuples:

var newList = Array.Empty<object>().Select(x => new { Month = 1, Year = 1 }).ToList();

for (var i = employmentYear;  i <= currentYear; i  )
{
    for (var x = employmentMonth; x <= currentMonth; x  )
    {
        newList.Add(new{ Month = x, Year = i});
    }
}

For newList I suppose something like new [] { list.ElementAtOrDefault(-1) }.ToList(); would work too.. Whatever trick you feel like pulling to get a list of ATs!

  • Related