How to get name of the properties which are null in the list along with a fixed property which should be always there in the list

Viewed 30

I'm trying to get a list which contains the name of the properties which have value equals to null along with a property(InvoiceNumber) which should be always there .

public class InvoiceDetails
{
     public string InvoiceNumber { get; set; }
     public string InvoiceClass { get; set; }
     public string ExpenseMethod { get; set; }
     public string FromDate { get; set; }
     public string ToDate { get; set; }
}

I have two set of code, (#1) -This only returns InvoiceNumber where other properties values mentioned in code are equal to null , this is the property which should be always there in the list. This (#2) returns the properties having value equal to null.But I want to somehow return list having InvoiceNumber along with the property name which were null.

(#1) var invoice= InvoiceDetails.Where(x => x.FromDate == null || x.ExpenseMethod == null || x.ToDate == null).Select(s => s.InvoiceNumber ).Distinct().ToList();

(#2) var result = typeof(InvoiceDetails).GetProperties()
        .Select(x => new { property = x.Name, value = x.GetValue(objInvoiceDetails) })
        .Where(x => x.value != null)
        .ToList();

E.g 101| FromDate |ExpenseMethod |
Here for invoice number 101 property FromDate and Expense method had null values

1 Answers
I'm trying to get a list which contains the name of the properties which have value equals to null along with a property(InvoiceNumber)

Sounds like you want to return a Dictionary<string, List<string>>

var dictionary = new Dictionary<string, List<string>>();
var nullInvoices = InvoiceDetails.
    Where(x => x.FromDate == null || x.ExpenseMethod == null || x.ToDate == null).
    Distinct();
foreach (var invoiceDetails in nullInvoices )
{
    var key = invoiceDetails.InvoiceNumber;
    var val = typeof(InvoiceDetails).GetProperties().
        Where(x => x.GetValue(invoiceDetails) == null).
        Select(x => x.Name).
        ToList();
    dictionary[key] = val;
}
Related