使用当前版本的代码:
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}");
}
,
如果您尝试仅检查至少一个ConstantA实例,则只需使用“ Any()”,如下所示:
if (stuff.Constants.Any(x => x.Key == "ConstantA")
{
//do something....
}
,
关于提出的问题,我建议使用 Linq 的两种不同方法,希望对您有用。
1-第一种方法:
_openGallery(BuildContext context) async{
var picture = await ImagePicker.pickImage(source: ImageSource.gallery);
this.setState((){
imageFile=picture;
});
Directory pathd = await getApplicationDocumentsDirectory();
String path =pathd.path;
final File newImage = await imageFile.copy('$path/name.jpg');
Navigator.of(context).pop();
}
2-第二种方法:
var result = listOfStuff.SelectMany(e => e.Constants.Select(d => d))
.Where(e=> e.Key == "ConstantA");
本文链接:https://www.f2er.com/2425570.html