使用LINQ计算C#中的年龄

时间:2015-09-01 08:58:51

标签: c# linq

我想根据他的出生日期计算客户年龄。

public List<ProductView> GetProductsByStoreAndCategoryID(string storeId, string categoryId)
{
    Authenticate();
    int _storeId = Convert.ToInt32(storeId);
    int _categoryId = Convert.ToInt32(categoryId);

    //selecting customerid
    var _customerId = (from cs in context.customerstores.Where(cs => cs.StoreId == _storeId && cs.IsDefault.Equals(true)) select cs.CustomerId).FirstOrDefault();

    //getting customer date of birth for calculating age and excluding regulated product from the list
    var _DateOfBirth = (from c in context.customers.Where(c => c.CustomerId == _customerId && c.IsBlocked.Equals(false)) select c.DateOfBirth).FirstOrDefault();
}

我在这里得到了出生日期,之后我想根据出生日期计算年龄。怎么做?

3 个答案:

答案 0 :(得分:1)

就像是:

var today = DateTime.Today;

var age = today.Year - _DateOfBirth.Year ; ////If _DateOfBirth is a DateTime  object

if (_DateOfBirth > today.AddYears(-age)) age--;

答案 1 :(得分:0)

未经测试......但应该可以使用。

    public static int GetAge(DateTime customerDateOfBirth)
    {
        var now = DateTime.UtcNow;
        var customerAge = now.Year - customerDateOfBirth.Year;
        if (customerDateOfBirth > now.AddYears(-customerAge)) 
            customerAge--;
        return customerAge;
    }

答案 2 :(得分:0)

var _DateOfBirth = (from c in context.customers.Where(c => c.CustomerId == _customerId && c.IsBlocked.Equals(false)) select c.DateOfBirth).FirstOrDefault();
    Console.WriteLine(_DateOfBirth.Year);
    Console.WriteLine(_DateOfBirth.Day);
    Console.WriteLine(_DateOfBirth.Month);

您可以从上面的代码中计算年龄