Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Linq Condition Contains

I cannot seem to get the desirable filtered result from my query.

Data

public class fdp_1115
{
    public string Id{ get; set; }
    public string Number{ get; set; }
    public string Type{ get; set; }
} 

List<fdp_1115> fdpList = new List<fdp_1115> {
    new fdp_1115 { Id = "1", Number = "Lot123", Type = "D14MWT" },
    new fdp_1115 { Id = "2", Number = "Lot123", Type = "E12WBC7W1" }
};
List<string> searchValues = new List<string> { "MLE12WBC7W1 A R" };

Linq:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var LocType = fdpList.FirstOrDefault(d => searchValues.Any(s => d.Type.Contains(s)));

if (LocType != null)
{
    Console.WriteLine("Matching record found:");
    Console.WriteLine($"Id: {LocType.Id}, Number: {LocType.Number}, Type: {LocType.Type}");
}
else
{
    Console.WriteLine("No matching records found.");
}

The result I wanted is :

Matching record found:
Id: 2, Number: Lot123, Type: E12WBC7W1

But I got "No matching records found." which indicates that LocType == null.
I already tried trimming and ignoring case sensitive:

var LocType = fdpList.FirstOrDefault(d => searchValues.Any(s => d.Type.Contains(s.Trim().Replace(" ", ""))));
var LocType = fdpList.FirstOrDefault(d => searchValues.Any(s => d.Type.Contains(s, StringComparison.InvariantCultureIgnoreCase)));

But still no luck. Any idea how do I match MLE12WBC7W1 A R with E12WBC7W1

>Solution :

Your current logic checks whether there is any object with Type value that contains the value for each string in the searchValues array.

From your requirement:

You want to filter the object that fulfills there is any string in searchValues containing the value of Type.

Thus it should be:

var LocType = fdpList.FirstOrDefault(d => searchValues.Any(s => s.Contains(d.Type)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading