简体   繁体   English

使用Linq选择Id(s)

[英]Select Id(s) using Linq

I have a DynamicNode named products which has product name and product id. 我有一个名为products的DynamicNode产品,它有产品名称和产品ID。 I need to select all products id's to a array from the DynamicNode products using LINQ. 我需要使用LINQ从DynamicNode产品中选择所有产品id到数组。

I tried something like 我试过类似的东西

 @helper PrintProductYearChart(IEnumerable<DynamicNode> products)
{

    var res = products.select(x => x.filelds['Id']).ToAarray();
}

but its not working correctly. 但它不能正常工作。

Can any one help.Thanks in advance 任何人都可以提供帮助。谢谢

The Select LINQ operator Projects each element of a sequence into a new form. Select LINQ运算符将序列的每个元素投影到新表单中。 what you are you doing will project only one element with 'Id' as index so it will return one element only not an array of Id's 你在做什么只会投射一个'Id'作为索引的元素,所以它只返回一个元素而不是Id的数组

here you should specifiy that you want the ID 在这里你应该指明你想要的ID

   @helper PrintProductYearChart(IEnumerable<DynamicNode> products)
    {

        var res = products.select(x => x.Id).ToArray();
    }
class Program
{
    static void Main(string[] args)
    {
        var collection = new List<DynamicNode>(){
            new DynamicNode { Id = "1", Name = "name1"},
            new DynamicNode { Id = "2", Name = "name2"}
        };

        //Getting Ids using extension methods and lambda expressions
        string[] Ids = collection.Select(x => x.Id).ToArray();

        foreach (string id in Ids)
            Console.WriteLine(id);

        //Gettings ids using linq expression
        var linqIds = from s in collection
                           select s.Id;
        string[] lIds = linqIds.ToArray();

        foreach (string id in lIds)
            Console.WriteLine(id);

        Console.Read();
    }
}

class DynamicNode
{
    public string Id { get; set;}
    public string Name { get; set; }
}

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

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