简体   繁体   中英

Querying IList using LINQ

Is foreach is the only option to get the property values of an object? (if I store that in var type)

IList<SampleClass> samples = GetIList();
var onesample = samples.Select(p => p.Propy == "A").FirstOrDefault();

do I need to loop through 'onesample' to get the values using foreach or any better way?

Just try with this.

IList<SampleClass> samples = GetIList();
SampleClass onesample = samples.FirstOrDefault(p => p.Propy == "A");

you dont need select or where ...you can just apply lambda express on the FirstOrDefault

 IList<SampleClass> samples = GetIList();
 var onesample = samples.FirstOrDefault(p => p.Propy == "A");

I know that the OP's question is totally unhelpfully formulated, but in case someone found himself here (as me) because he wanted to use LINQ with IList (one good example is trying to get a selected item inside WPF Combobox's SelectionChanged handler), here's my solution:

Cast IList to IEnumerable<T> :

private void Combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string item = ((IEnumerable<object>)e.AddedItems).FirstOrDefault() as string;
            Console.WriteLine($"Combo item is: '{item}'");
        }
IList<SampleClass> samples = GetIList();
var onesample = samples.Select(p => p.Propy == "A").FirstOrDefault();

Should be..

IList<SampleClass> samples = GetIList();
var onesample = samples.Where(p => p.Propy == "A").FirstOrDefault();

This will get you one instance of SampleClass

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