How to Get a Sublist in C#

前端 未结 6 1549
走了就别回头了
走了就别回头了 2021-02-02 05:09

I have a List and i need to take a sublist out of this list. Is there any methods of List available for this in .NET 3.5?

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 05:27

    Use the Where clause from LINQ:

    List x = new List();
    x.Add("A");
    x.Add("B");
    x.Add("C");
    x.Add("D");
    x.Add("B");
    
    var z = x.Where(p => p == "A");
    z = x.Where(p => p == "B");
    
    
    

    In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:

    public class Client
    {
        public string Name { get; set; }
    }
    

    then your linq would look like this:

    List x = new List();
    x.Add(new Client() { Name = "A" });
    x.Add(new Client() { Name = "B" });
    x.Add(new Client() { Name = "C" });
    x.Add(new Client() { Name = "D" });
    x.Add(new Client() { Name = "B" });
    
    var z = x.Where(p => p.Name == "A");
    z = x.Where(p => p.Name == "B");
    

    提交回复
    热议问题