如何使用 lambda 表达式过滤 C# 中的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9799109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:54:29  来源:igfitidea点击:

How to filter a list in C# with lambda expression?

c#lambda

提问by user603007

I am trying to filter a list so it results in a list with just the brisbane suburb?

我正在尝试过滤一个列表,以便生成一个仅包含布里斯班郊区的列表?

c#

C#

Temp t1 = new Temp() { propertyaddress = "1 russel street",  suburb = "brisbane" };
            Temp t2 = new Temp() { propertyaddress = "12 bret street", suburb = "sydney" };
            List<Temp> tlist = new List<Temp>();
            tlist.Add(t1);
            tlist.Add(t2);

            List<Temp> tlistFiltered = new List<Temp>();
            //tlistFiltered. how to filter this so the result is just the suburbs from brisbane?

public class Temp
    {
        public string propertyaddress { get; set; }
        public string suburb { get; set; }
    }

采纳答案by Despertar

Use Whereclause to filter a sequence

使用Where子句过滤序列

 var tlistFiltered = tlist.Where(item => item.suburb == "brisbane")

LINQ expressions like Where return IEnumerable<T>. I usually capture the result with var but you could use ToList()to project the result to a list as well. Just depends what you need to do with the list later.

LINQ 表达式,如 Where return IEnumerable<T>。我通常使用 var 捕获结果,但您也可以使用ToList()将结果投影到列表中。只取决于您稍后需要对列表做什么。

List<Temp> tlistFiltered = tlist
    .Where(item => item.suburb == "brisbane")
    .ToList()

Note that with the above you don't have to allocate a new list. The Whereand ToList()methods both return a new sequence which you just need to capture with the reference.

请注意,使用上述内容,您不必分配新列表。该WhereToList()方法均返回,你只需要捕获与参考的新序列。