Pop
Pop

Reputation: 525

C# Return true if string is different from any of the string in a list of strings using LINQ

How do I achieve the same result as code below using LINQ?

What it do is if a string is different from any of the string in a list of strings, it will return true.

public static bool MasterPlantDifferentFromDetailPlant(string mrNumber)
{
    string masterPlant = t_MT_MTInfo.GetMaterialRequestPlant(mrNumber);
    List<string> detailPlants = t_MT_MTItem.GetPlants(mrNumber);
    bool differentPlant = false; 
    foreach (string plant in detailPlants)
    {
        if (string.Compare(masterPlant.Trim(), plant.Trim(), StringComparison.OrdinalIgnoreCase) != 0)
        {
            differentPlant = true;
            break;
        }
    }
    return differentPlant;
}

Upvotes: 0

Views: 238

Answers (2)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

Try like this;

    public static bool MasterPlantDifferentFromDetailPlant(string mrNumber)
    {
        string masterPlant = t_MT_MTInfo.GetMaterialRequestPlant(mrNumber);
        List<string> detailPlants = t_MT_MTItem.GetPlants(mrNumber);
        return !detailPlants.All(x => string.Equals(masterPlant.Trim(), x.Trim(), StringComparison.OrdinalIgnoreCase));
    }

Upvotes: 0

Jeff F.
Jeff F.

Reputation: 1067

detailPlants.Any(p => string.Compare(masterPlant.Trim(), p.Trim(), StringComparison.OrdinalIgnoreCase) != 0)

Upvotes: 4

Related Questions