C# Looping through a list and extracting specific data

时间:2019-04-08 14:03:29

标签: c#

I need to loop through a list of type TrackRecordVM and extract data from fields that are only assigned to fields names Jan, Feb, Mar,Apr, May, Jun, July,Aug,Sep,Oct,Nov,Dec

This is the list that I am looping through

public class TrackRecordVM
{
    public int Year { get; set; }
    public decimal? Jan { get; set; }
    public decimal? Feb { get; set; }
    public decimal? Mar { get; set; }
    public decimal? Apr { get; set; }
    public decimal? May { get; set; }
    public decimal? Jun { get; set; }
    public decimal? Jul { get; set; }
    public decimal? Aug { get; set; }
    public decimal? Sep { get; set; }
    public decimal? Oct { get; set; }
    public decimal? Nov { get; set; }
    public decimal? Dec { get; set; }
    public decimal? YTD { get; set; }
    public decimal? Bmrk { get; set; }
    public string BmrkName { get; set; }
}

Here is the loop. Whats the best way of doing it

 List<TrackRecordVM> trackRecordVm;

            foreach (var trackRecord in fundTrackRecord)
            {
                trackRecordVm = trackRecord.TrackRecord;

                foreach (var track in trackRecordVm)
                {


                }
            }

2 个答案:

答案 0 :(得分:1)

You'd probably have an easier time with Linq.

Something along the lines of this (just repeat this for whichever members you need):

var jan = trackRecordVm.Select(x => x.Jan).ToList();

var dec = trackRecordVm.Select(x => x.dec).ToList();

var newList = new List<decimal?>(); newList.AddRange(jan); newList.AddRange(dec);

答案 1 :(得分:0)

我不喜欢这样,但是您可以完全按照以下要求进行操作:

    public static void DoIt()
    {
        TrackRecordVM record = new TrackRecordVM();

        string[] months = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };

        foreach (decimal? value in record.GetType().GetRuntimeProperties()
            .Where(p => months.Contains(p.Name))
            .Select(pi => pi.GetValue(record, null)))
        {
            //do stuff
        }
    }

或者,您可以在记录类中创建一个枚举,如下所示:

public class TrackRecordVM
{
    public decimal? Jan { get; set; }
    public decimal? Feb { get; set; }
    public decimal? Not { get; set; }

    public IEnumerable<decimal?> GetMonths()
    {
        yield return Jan;
        yield return Feb;
    }
}

我更喜欢第二种选择,我自己。