简体   繁体   English

使用 LINQ 查询 IList

[英]Querying IList using LINQ

Is foreach is the only option to get the property values of an object? foreach 是获取对象属性值的唯一选项吗? (if I store that in var type) (如果我将其存储在 var 类型中)

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?我是否需要遍历“onesample”以使用 foreach 或任何更好的方式获取值?

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你不需要 select 或 where ...你可以在 FirstOrDefault 上应用 lambda express

 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:我知道 OP 的问题完全没有帮助,但是如果有人发现自己在这里(就像我一样)因为他想将 LINQ 与 IList 一起使用(一个很好的例子是尝试在 WPF Combobox 的 SelectionChanged 处理程序中获取选定的项目),这是我的解决方案:

Cast IList to IEnumerable<T> :IListIEnumerable<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这将为您提供一个SampleClass实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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