Search code examples
c#asp.net-mvc-4asp.net-mvc-viewmodel

List items that contain a string value


I have a list of objects that has a string for phone number, I want to create a query to look for a list of objects that has any of the numbers.

here is the model:

public class ReportViewModel
    {
        public int QueueReportId { get; set; }
        public string Message { get; set; }
        public string PhoneNumber { get; set; }
        public bool Sent { get; set; }
        public DateTime Day { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime SentDate { get; set; }
    }

and I send a list of ReportViewModel to the view, is there a way to sort that list that is being sent to the view by phone number if the phone number is not an exact match?

for example, I would like to search on the list for objects that have a phone number that contains the area code 513 anywhere on the public string PhoneNumber { get; set; }

I know how to look for items with that are exactly the same, but not for something like this.

Any help would be appreciated.


Solution

  • You could use the Any() method and pass an expression to check it in the PhoneNumber string property with the Contains string method, for sample:

    // get your list
    List<ReportViewModel> reports = GetReports();
    
    string areaCode = "513";
    
    // check if any object has a phone value in any part of string
    if (reports.Any(r => r.PhoneNumber.Contains(areaCode)))
    {
       // contains the phone number
    }