LINQ查询以显示列表中是否存在ID

时间:2013-11-26 11:02:18

标签: c# sql linq

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())];
    }
}

我想检查 FPTStaticDataManagedStrategyAssetlist 中是否存在 asset.StaticDataManagedStrategyAsset.Name 。我不完全确定要使用哪个运算符?

2 个答案:

答案 0 :(得分:3)

使用Any

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

只要符合条件,它就会返回true

同样,对于字符串比较,如果您想要更多控制如何比较字符串(MSDN),则可以使用string.Equals(string, string, StringComparision)

答案 1 :(得分:3)

您应该更改使用Enumerable.Any的位置。

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