简体   繁体   中英

LINQ Query to show if ID exists in list

foreach (var asset in fpt.CouttsPositionSection.ManagedStrategyAssets)
{
var result = FPTStaticDataManagedStrategyAssetlist.Where(e => e.Name == asset.StaticDataManagedStrategyAsset.Name);
if (result == null)
    {
      asset.StaticDataManagedStrategyAsset = FPTStaticDataManagedStrategyAssetlist[random.Next(0, FPTStaticDataManagedStrategyAssetlist.Count())];
    }
}

I want to check if asset.StaticDataManagedStrategyAsset.Name exists in FPTStaticDataManagedStrategyAssetlist . I'm not entirely sure what operator to use?

Use Any :

if (!FPTStaticDataManagedStrategyAssetlist.Any(e => e.Name == asset.StaticDataManagedStrategyAsset.Name))
{
   //code
}

it will return true as soon as condition is met.

Also for string comparison you can use string.Equals(string, string, StringComparision) if you want more control how to compare strings ( MSDN ).

You should change where to use Enumerable.Any .

if(!FPTStaticDataManagedStrategyAssetlist.Any(e => e.Name == asset.StaticDataManagedStrategyAsset.Name))
{
    asset.StaticDataManagedStrategyAsset = FPTStaticDataManagedStrategyAssetlist[random.Next(0, FPTStaticDataManagedStrategyAssetlist.Count())];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM