简体   繁体   中英

Need to get a value from a collection?

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?

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);

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];
   string valueForL = "abc";
   List<Detail> details = new List<Detail>();
   string valueForR = (from d in details where d.L == valueForL select d.R).FirstOrDefault();

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

take a look at this thread about implementing the IEquatable interface. I guess you'll find all you need there.

怎么样:

IEnumerable<string> allR = Details.Where(d => Equals(d.L, otherString)).Select(d => d.R);

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.

您可以尝试LINQ to Objects:

string r = (from d in list where d.L.Equals(...) select d.R).FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM