I am trying to solve an issue where I want to filter values based on another list of values
List 1:
[
{"Number":"324234","PhoneType":"Cell"},
{"Number":"645645","PhoneType":"Work"},
{"Number":"3453453","PhoneType":"phone"},
{"Number":"342","PhoneType":"fax"}
]
List 2:
["Work","Cell","phone","Fax"]
Conditions: I want to filter list 1 based list 2 values in the given order.
provided list 2 wont be same in all condition, some times it will have only cell and work and some time it will have only work and sometimes it will have work,cell,phone and fax We don't need to consider phone type fax while we filtering as well as the order in the list 2 will be different each time
Example: List 2 is having work as a first value, if we have phone type work in list 1, then we need to get only that record from list 1, if list 1 does not have work then has to look for phone type cell as its a second value from list 2
I would like to solve this issue using Lamda functions or for each
My Attempt 1:
var results = List1.Where((item, index) => list2[index] == "work");
Here phone type should be from list 2
My Attempt 2
var primaryPhone = list1?.FirstOrDefault(p => !p.PhoneType.Equals("Fax") && !p.MediaType.Equals("Fax"));
The above line returns only the first record by default from List 1
Could some one help me to find the record from list 1 based on list 2 values in the given order
Try the following filter.
var listToFilter = new List<Phone>()
{
new() { Number = "324234", PhoneType = "Cell" },
new() { Number = "645645", PhoneType = "Work" },
new() { Number = "3453453", PhoneType = "Phone" },
new() { Number = "342", PhoneType = "Fax" }
};
var filterList = new[] { "Work", "Cell", "Phone", "Fax" };
Phone matchingPhone = null;
foreach (var filter in filterList)
{
matchingPhone = listToFilter.FirstOrDefault(p => p.PhoneType == filter);
if (matchingPhone is not null)
break;
};
Examples here: https://dotnetfiddle.net/d9pP3k
As a function:
private static Phone GetMatchingPhone(IEnumerable<Phone> phones, IEnumerable<string> filters)
{
foreach (var filter in filters)
{
var matchingPhone = phones.FirstOrDefault(p => p.PhoneType == filter);
if (matchingPhone is not null)
return matchingPhone;
};
return null;
}