CoolArchTek
CoolArchTek

Reputation: 3839

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?

Upvotes: 1

Views: 24905

Answers (4)

z33k
z33k

Reputation: 3636

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

Upvotes: 0

Thilina H
Thilina H

Reputation: 5804

Just try with this.

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

Upvotes: 4

Dan Hunex
Dan Hunex

Reputation: 5318

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

Upvotes: 0

Christian Phillips
Christian Phillips

Reputation: 18759

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

Upvotes: -1

Related Questions