Select Id(s) using Linq
Asked Answered
E

2

9

I have a DynamicNode named products which has product name and product id. I need to select all products id's to a array from the DynamicNode products using LINQ.

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

Engleman answered 18/1, 2014 at 8:57 Comment(6)
How do the actual and the expected answer differ?Drabeck
in the products.select and x.fields['Id'] having error.Can't resolve the symbolEngleman
What does the public interface of DynamicNode look like?Drabeck
What type of information do you need from me.you clarify above comment ?Engleman
What is DynamicNode defined like? What properties and methods does it have? (Only with that knowledge, we can tell what filelds does or what to use instead.)Drabeck
Also, is it really filelds (in capital letters: FILELDS) or fileIds (in capital letters: FILEIDS)?Drabeck
B
19

The Select LINQ operator Projects each element of a sequence into a new form. 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

here you should specifiy that you want the ID

   @helper PrintProductYearChart(IEnumerable<DynamicNode> products)
    {

        var res = products.select(x => x.Id).ToArray();
    }
Bitternut answered 18/1, 2014 at 8:59 Comment(0)
S
4
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; }
}
Seth answered 18/1, 2014 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.