c#如何访问List< Class>的元素 [英] c# How To Access Elements of a List<Class>

查看:539
本文介绍了c#如何访问List< Class>的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问类列表"中的某个字段,以便可以在循环中进行计算.

I want to access a certain field within a Class List so that I can do a calculation within a loop.

首先是我的课:

public class Hold
{
    public DateTime Time { get; set; }
    public Double XPosition { get; set; }
    public Double YPosition { get; set; }
}

然后我的列表List<Hold>Data;

然后我使用Linq存储查询中的值.

I then use Linq to Store values from a Query.

我理想地要做的是像这样访问List的Time部分:

What I ideally want to do is access the Time part of the List like so:

for(int i =0; i < Data.Count; i++)
{
    double average = Data.Time  // etc etc
}

推荐答案

寻找简单的foreach吗?

Looking for a simple foreach?

foreach(Hold h in Data)
{
     DateTime t = h.Time;

     ... other properties or whatever method defined for the class Hold
}

List<T>实现 IEnumerator 接口,因此当您需要遍历List的所有元素并提取其对象时,可以使用foreach

A List<T> implements the IEnumerator interface, so it is natural to use foreach when you need to loop over all the elements of the List and extract its objects

foreach方法唯一可能的问题是,如果需要在遍历元素时将其从列表中删除.但是,如果您不需要这样做,那么foreach是访问列表中包含的元素的最简单自然的方法.

The only possible problem with the foreach approach is if you need to remove elements from the list while iterating over them. But if you don't need this, then foreach is the most simple and natural way to access the elements contained in the list.

但是,知道您要在循环中执行的操作会很有趣.
也许有一些更简单的方法可以使用Linq并完全删除循环.

However it would be interesting to know what you want to do inside the loop.
Perhaps there are simpler ways using Linq and completely remove the loop.

例如,如果要计算列表中存储的时间"值的平均秒数,则可以使用

For example, if you want to calculate the average seconds of your Time values stored in the list you could remove the loop using

 var k = data.Select(x => new TimeSpan(x.Time.Hour, x.Time.Minute, x.Time.Second))
             .Average(z => z.TotalSeconds);

这篇关于c#如何访问List&lt; Class&gt;的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆