Friday, August 12, 2022

[FIXED] How to assign to a list of decimal and to a list of string from a list property object and compare decimal

Issue

How to assign to a list of decimal and also a list of string from a input I get as a list. Some sample code below. Also, once Assigned decimal list I also need to compare it and if it equals, then do something.

public partial class Person
    {
        [DataMember]
        public string ID { get; set; }

        [DataMember]
        public decimal Amount{ get; set; }
}


public class Details
{
 public List<Person> PersonList { get; set; }
}

List<decimal> Amount = Details.PersonList.Amount;
List<string> ID = Details.PersonList.ID;

if(Amount == decimal.Parse($100, NumberStyles.Currency))
 // do something

Solution

Use Linq:

List<decimal> amounts = details.PersonList.Select(x => x.Amount).ToList();
List<string> ids = details.PersonList.Select(x => x.ID).ToList();

You do not need Parse to specify an amount at compile-time:

if (someAmount == 100m)
{
  // do something
}


Answered By - Jeppe Stig Nielsen
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.