Reputation: 667
I'm trying to use LINQ to find a specific string value "ConstantA" in a List.
Variable "stuff" is a type of:
List<KeyValuePair<string, string>>
The first value in the List (StuffName) is the one that I'm looking for:
How do I use LINQ to find the correct StuffName = "ConstantA"?
This is my code below:
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; }
}
Upvotes: 2
Views: 95
Reputation: 1553
Concerning the problem raised, I propose two different approaches both of them using Linq hoping that you will be useful .
1 - First Approache :
var result = listOfStuff.SelectMany(e => e.Constants.Select(d => d))
.Where(e=> e.Key == "ConstantA");
2 - Second Approache :
var result = from item in listOfStuff.SelectMany(e => e.Constants)
where item.Key =="ConstantA"
select item ;
Upvotes: 1
Reputation: 8330
With your current version of code:
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**
}
}
In case if you don't want items but only want to check condition, use LINQ Any
method:
foreach (var stuff in listOfStuff)
{
if (stuff.Constants.Any((keyValuePair) => keyValuePair.Key == "ConstantA"))
{
{
//**I’m having problem with LINQ here**
}
}
}
In case if your Stuff
class is defined using Dictionary
:
public class Stuff
{
public Dictionary<string, string> Constants { get; set; }
}
and usage:
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**
}
}
Note that with both cases usage is same, which means changing
List<KeyValuePair<string, string>>
toDictionary<string, string>
will not affect much code.
And finally a version I prefer the most )
The Stuff
class would be:
public class Stuff
{
public string StuffName { get; set; }
public int StuffValue { get; set; }
}
Next, the calculate method would be:
private static List<Stuff> CalculateStuff()
{
return new List<Stuff>()
{
new Stuff{StuffName = "ConstantA", StuffValue = 100},
new Stuff{StuffName = "ConstantB",StuffValue = 200}
};
}
And the usage:
var listOfStuff = CalculateStuff().Where(st =>
st.StuffName == "ConstantA");
foreach (var stuff in listOfStuff)
{
Console.WriteLine($"Name: {stuff.StuffName}, Value: {stuff.StuffValue}");
}
Upvotes: 1
Reputation: 5106
If you're trying to just check for at least one instance of ConstantA then just use 'Any()' like this:
if (stuff.Constants.Any(x => x.Key == "ConstantA")
{
//do something....
}
Upvotes: 1