2

我正在尝试使用 LINQ 在列表中查找特定的字符串值“ConstantA”。

变量“stuff”是一种类型:

List<KeyValuePair<string, string>> 

列表 (StuffName) 中的第一个值是我要查找的值:

在此处输入图像描述

如何使用 LINQ 找到正确的 StuffName = "ConstantA"?

这是我下面的代码:

var listOfStuff = CalculateStuff();
foreach (var stuff in listOfStuff)
{
  if (stuff.Constants.FindAll("ConstantA") //**I’m having problem with LINQ here**
  {
   …
  }
}


private static List<Stuff> CalculateStuff()
{
…
}

public class Stuff : IHasIntInst
{
    public List<KeyValuePair<string, string>> Constants { get; set; }
}
4

3 回答 3

1

关于提出的问题,我提出了两种不同的方法,它们都使用Linq,希望对您有所帮助。

1 - 第一种方法:

var result = listOfStuff.SelectMany(e => e.Constants.Select(d => d))
                        .Where(e=> e.Key == "ConstantA");

2 - 第二种方法:

 var result = from item in listOfStuff.SelectMany(e => e.Constants)
             where item.Key =="ConstantA"
             select item ;
于 2020-04-16T21:40:00.597 回答
1

使用您当前版本的代码:

var listOfStuff = CalculateStuff();
foreach (var stuff in listOfStuff)
{
    var items = stuff.Constants.FindAll((keyValuePair) => keyValuePair.Key == "ConstantA");
    if (items.Any())
    {
        //**I’m having problem with LINQ here**
    }
}

如果您不想要项目但只想检查条件,请使用LINQ Any方法:

foreach (var stuff in listOfStuff)
{
    if (stuff.Constants.Any((keyValuePair) => keyValuePair.Key == "ConstantA"))
    {
        {
            //**I’m having problem with LINQ here**
        }
    }
}

如果您的Stuff类是使用定义的Dictionary

public class Stuff
{
    public Dictionary<string, string> Constants { get; set; }
}

和用法:

var listOfStuff = CalculateStuff();
foreach (var stuff in listOfStuff)
{
    var items = stuff.Constants.Where((kvp) => kvp.Key == "ConstantA");

    if (items.Any())
    {
        //**I’m having problem with LINQ here**
    }
}

请注意,这两种情况的用法是相同的,这意味着更改 List<KeyValuePair<string, string>>Dictionary<string, string>不会影响太多代码。


最后是我最喜欢的版本)
课程Stuff是:

public class Stuff
{
    public string StuffName { get; set; }
    public int StuffValue { get; set; }
}

接下来,计算方法将是:

private static List<Stuff> CalculateStuff()
{
    return new List<Stuff>()
    {
        new Stuff{StuffName = "ConstantA", StuffValue = 100},
        new Stuff{StuffName = "ConstantB",StuffValue = 200}

    };
}

以及用法:

var listOfStuff = CalculateStuff().Where(st => 
                                         st.StuffName == "ConstantA");

foreach (var stuff in listOfStuff)
{
    Console.WriteLine($"Name: {stuff.StuffName}, Value: {stuff.StuffValue}");
}
于 2020-04-16T18:51:20.110 回答
1

如果您只想检查ConstantA 的至少一个实例,那么只需像这样使用'Any()':

if (stuff.Constants.Any(x => x.Key == "ConstantA")
{
    //do something....
}
于 2020-04-16T18:53:15.190 回答