question

MarkusFreitag-0088 avatar image
0 Votes"
MarkusFreitag-0088 asked karenpayneoregon commented

C# lambda - small question

Hello,

Need I here ToString() override?
Why can't I debug this? I can't get into GetAge.

//~~~~~

       public void Test()
             {
       
                 User[] users =
                     {
                   new User (1, "John", "London", "2001-04-01"),
                   new User(2, "Lenny", "New York", "1997-12-11"),
                   new User(3, "Andrew", "Boston", "1987-02-22"),
                   new User(4, "Peter", "Prague", "1936-03-24"),
                   new User(5, "Anna", "Bratislava", "1973-11-18"),
                   new User(6, "Albert", "Bratislava", "1940-12-11"),
                   new User(7, "Adam", "Trnava", "1983-12-01"),
                   new User(8, "Robert", "Bratislava", "1935-05-15"),
                   new User(9, "Robert", "Prague", "1998-03-14")
                 };
        
                 var country = "Bratislava";
                 Func<User, bool> livesIn = e => e.Country == country;
        
                 var res = users.Where(livesIn);
        
                 foreach (var e in res)
                 {
                     Console.WriteLine(e);
                 }
        
                               
                 var users2 = new List<User>
                         {
                           new User(1, "John", "London", "2001-04-01"),
                           new User(2, "Lenny", "New York", "1997-12-11"),
                           new User(3, "Andrew", "Boston", "1987-02-22"),
                           new User(4, "Peter", "Prague", "1936-03-24"),
                           new User (5, "Anna", "Bratislava", "1973-11-18"),
                           new User (6, "Albert", "Bratislava", "1940-12-11"),
                           new User(7, "Adam", "Trnava", "1983-12-01"),
                           new User (8, "Robert", "Bratislava", "1935-05-15"),
                           new User(9, "Robert", "Prague", "1998-03-14"),
                         };
        
                 var age2 = 60;
                 Func<User, bool> olderThan = e => GetAge(e) > age2;
        
                 var res2 = users.Where(olderThan);
        
                 foreach (var e in res)
                 {
                     Console.WriteLine(e);
 // Need I here ToString() override?
                 }
        
             }
    
 //Why can't I debug this? I can't get into GetAge.
    
       int GetAge(User user)
             {
                 var dob = DateTime.Parse(user.Birthday);
                 return (int)Math.Floor((DateTime.Now - dob).TotalDays / 365.25D);
             }



dotnet-csharpwindows-forms
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Just checking - it looks like you're enumerating res instead of res2 (the one that predicates on olderThan & by calling GetAge.) Was that deliberate?

1 Vote 1 ·

Ups,
you're right. Thanks. How would you do the output?

 foreach (var e in res)
         {
         Console.WriteLine(e);


0 Votes 0 ·
karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered MarkusFreitag-0088 commented

Here is a simple example done in a console project.

The console project uses two class project, BaseDataValidatorLibrary for validating models and uses System.ComponentModel.Annotations NuGet package, The second class project, BaseModelsLibrary has various models to validate.

If this works for you, clone the repository, all you need is the BaseDataValidatorLibrary class project.

Here is the example from my first reply in a console project.
197396-screenshot.png

 using System;
 using BaseDataValidatorLibrary.Helpers;
 using BaseModelsLibrary.Models;
 using static System.DateTime;
    
 namespace PersonValidationConsole
 {
     class Program
     {
         static void Main(string[] args)
         {
             PersonIsValid();
             Console.WriteLine();
             PersonIsNotValid();
                
             Console.ReadLine();
         }
    
         private static void PersonIsNotValid()
         {
             Title(nameof(PersonIsNotValid));
             Person person = Person;
             person.BirthDate = new DateTime(1931, Now.Month, Now.Day);
    
             EntityValidationResult result = Model.Validate(person);
    
             if (result.IsValid)
             {
                 Console.WriteLine("Valid");
             }
             else
             {
                 foreach (var error in result.Errors)
                 {
                     Console.WriteLine(error.ErrorMessage);
                 }
             }
         }
    
         private static void PersonIsValid()
         {
             Title(nameof(PersonIsValid));
             Person person = Person;
                
             EntityValidationResult result = Model.Validate(person);
    
             if (result.IsValid)
             {
                 Console.WriteLine("Valid");
             }
             else
             {
                 foreach (var error in result.Errors)
                 {
                     Console.WriteLine(error.ErrorMessage);
                 }
             }
         }
    
         private static Person Person => new()
         {
             FirstName = "Mike",
             LastName = "Flowers",
             BirthDate = new DateTime(1932, Now.Month, Now.Day)
         };
    
         private static void Title(string sender)
         {
             Console.ForegroundColor = ConsoleColor.White;
             Console.Write("Running");
             Console.ResetColor();
             Console.Write($" {sender}\n");
         }
     }
 }

Note that there are a good deal of code samples in the repository to learn from, most are done in unit test and one in ASP.NET Core Razor.


screenshot.png (8.4 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks for your help.

0 Votes 0 ·
karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered karenpayneoregon commented

There is no built in tools to debug into your method. Best recommendation is to use LINQPad and use it's Dump method or OzCode.


· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks!

Ok that is a pity and complicated.

Do you have another idea tip how I do easier with the spelling.


 protected override void Execute()
 {
     Assert.ProgramSequence("RadioSensor", 10, sequence: (ps) =>
     {
         ps.OnValid += (req) =>
         {
             if (req.Data.side == Radio.Side1 && req.Data.number == 4)
                 req.Data.Check = "valid";
         };
     });
 }

Partly I see such a code.
How can one come up with this notation?

How could I write the above code differently or 'normal'?
Do you have a tip ?

0 Votes 0 ·

High level, I would take a different approach, create a custom rule using data annotations. The following example has nothing to do with your code, it's conceptual.

 [ValidateYears(ErrorMessage = "Valid range for BirthDate is {0} and {1}")]
 public DateTime BirthDate { get; set; }

The code behind

 public class ValidateYearsAttribute : ValidationAttribute
 {
     private readonly DateTime _minValue = DateTime.UtcNow.AddYears(-90);
     private readonly DateTime _maxValue = DateTime.UtcNow;
    
     public override bool IsValid(object sender)
     {
         var value = (DateTime)sender;
         return value.Year >= _minValue.Year && value.Year <= _maxValue.Year;
     }
    
     public override string FormatErrorMessage(string name) 
         => string.Format(ErrorMessage!, 
             _minValue.ToString("yyyy"), 
             _maxValue.ToString("yyyy"));
 }

Then use this code to validate.


1 Vote 1 ·

OK. Thanks.

197198-ok003.png



I think I need this package too.
Can you make a whole sample, how to call it?

0 Votes 0 ·
ok003.png (18.7 KiB)
Show more comments