mahesh
mahesh

Reputation: 3207

get specific properties within the generic list using linq

I have generic list foo as shown below

var foo = new List<XYZ>();
public class XYZ
{
    public String TimeZone { get; set; }
    public Decimal? B1Volume { get; set; }
    public Decimal? B2Volume { get; set; }
    public Decimal? B3Volume { get; set; }
    public Decimal? B4Volume { get; set; }
    public Decimal? B5Volume { get; set; }
    // .............
    // .............
    public Decimal? B24Volume { get; set; }
    public String Name {get;set;}
}

how do I select the properties B1Volume,........B24Volume ?

I tried with following code mentioned below, but it's not giving expected results

var hp = foo.Skip(1).Take(23).ToList();

Upvotes: 0

Views: 1635

Answers (3)

Farzin Kanzi
Farzin Kanzi

Reputation: 3435

Maybe it helps:

XYZ xyz = new XYZ();
Type t = xyz.GetType();
List<PropertyInfo> properties = new List<PropertyInfo>(t.GetProperties());
var hp = properties.Skip(1).Take(23).ToList();

Do not forget adding name space:

using System.Reflection;

Update

In comments GBreen12 suggests to add a filter for getting only properties that has name containing volume. Now if you add another properties the code will not fail. So you can change the 3th line to this:

List<PropertyInfo> properties = (new List<PropertyInfo>(t.GetProperties())).Where(x => x.Name.EndsWith("Volume")).ToList();

Now you do not need last line var hp = ... and the properties is your answer.

Upvotes: 0

GBreen12
GBreen12

Reputation: 1900

You need to do a Select:

var hp = foo.Select(x => new { x.BVolume1, x.BVolume2, ..., x.BVolume24 });

Although I do agree with @Himzo that this is not the best way to solve your problem if you can change the structure.

Upvotes: 1

Himzo Tahic
Himzo Tahic

Reputation: 151

There's a few ways, but I do not think that you want to go down that road. Do you really want a list of xyz? Or asked in a different fashion: Do you have many different lists of lists of volumes? Or do you only want to express a single list of volumes?

Maybe what you want to do is declare an array inside XYZ like this

public class XYZ
{
    public String TimeZone { get; set; }
    public Decimal?[] Volumes {get; set;} = new Decimal?[24];
    public String Name {get; set;}
}

If you want to access volumes by an index (1,2,...,24) you need an array or any other kind of indexed data structure.

Then you could do

var xyz = new XYZ();
xyz.Volumes[0] = 12.0;
xyz.Volumes[1] = 23.0;
.....

and basically access the volumes by xyz.Volumes and adding an index to get the n-th volume

If you now want to further list these XYZ you could do something like this:

var listOfXyz = new List<XYZ>();
listOfXyz.Add(new XYZ());
....
listOfXyz[3].Volumes

this would give you the 24 volumes of the element at the index of 3 in the list.

Upvotes: 1

Related Questions