Home > Enterprise >  How to select exact string from List?
How to select exact string from List?

Time:08-04

I have Json List

    {
        country: "INDIA      "
        },
 {
        country: "INDIA      "
        },
        {
        country: "INDIANA    "
        },
        {
    country: "AFRICA      "
        }

I am filtering country from the List which I have

var flights = new List<allflights>();
flights = flights.Where(x => x.Country.Contains(selectedvalue)).ToList();

In the above case if I select INDIA, INDIANA is also added to the List. But I want to pick only exact country which I am selecting. Need all the INDIA items to be added to the list. Don't want any other items to be added.

CodePudding user response:

You can modify your linq expression like below

flights.Where(x => x.Country.Equals(selectedvalue)).ToList();

Note: You can add additional code to trim the strings to fine tune per your needs

CodePudding user response:

you have to trim strings before comparing and use == instead of contains

var selectedvalue="INDIA";

List<allflights> selectedFlights = allFlights
.Where(a=> a.Country.Trim() == selectedvalue.Trim())
.ToList();

I can't see your data, so maybe you will need to use

a.Country.Trim().ToLower() == selectedvalue.Trim().ToLower())
  • Related