Reputation: 3
I have a variable of type List<Detail>
public class Detail {
public string L { get; set; }
public string R { get; set; }
}
I also have the value of a string that matches the value in Detail.L.
Is there an easy way that I can get the value of Detail.R that matches this?
Upvotes: 0
Views: 129
Reputation: 846
Like this to get all matching lefts:
IEnumerable<string> matchRightsToLeft(List<Detail> list, string left)
{
return list.Where(l => l.left == left).Select(l => l.right);
}
or for the first/only match
string matchRightToLeft(List<Detail> list, string left)
{
return list.Where(l => l.left == left).FirstOrDefault(l => l.right);
}
Upvotes: 1
Reputation: 3621
string valueForL = "abc";
List<Detail> details = new List<Detail>();
string valueForR = (from d in details where d.L == valueForL select d.R).FirstOrDefault();
Upvotes: 1
Reputation: 56697
You might try LINQ to Objects:
string r = (from d in list where d.L.Equals(...) select d.R).FirstOrDefault();
Upvotes: 0
Reputation: 60694
If L is unique as it seems in your case, it would be better to use a Dictionary here instead of a List.
var myList = new Dictionary<string,string>();
Then use L as the key and R as the value for the dictionary.
Add entries by calling myList.Add(newL,newR);
Then get a entry by doing this:
string myR = myList[myL];
Upvotes: 1
Reputation: 3802
A for-loop would be the basic way to do it.
Otherwise use Linq:
var lString = SearchValue;
DetailList.Where(o => o.R == lString) //This will give you a list of all the Detail object where R == lString.
Upvotes: 0
Reputation: 27055
How about:
IEnumerable<string> allR = Details.Where(d => Equals(d.L, otherString)).Select(d => d.R);
Upvotes: 0
Reputation: 2230
take a look at this thread about implementing the IEquatable interface. I guess you'll find all you need there.
Upvotes: 0
Reputation: 1499830
Sure, using LINQ to Objects (assuming you're using .NET 3.5 or higher):
string searchText = "the string to look for";
var matchingR = details.First(d => d.L == searchText).R;
Obviously that will find the first match. If you want to get all matches, you can do:
var matchingRs = details.Where(d => d.L == searchText)
.Select(d => d.R);
Upvotes: 2