gpt4 book ai didi

c# - 使用 lambda 函数合并包含不同对象的列表

转载 作者:行者123 更新时间:2023-12-02 05:08:23 31 4
gpt4 key购买 nike

我有三个不同的 List<string>包含不同类型数据的等长 s。例如:

List<string> dates = new List<string>() { "20120301", "20120401", "20120501", "20120601", "20120701"};
List<string> times = new List<string>() { "0500", "0800", "0100", "1800", "2100" };
List<string> quantities = new List<string>() { "1", "2", "1", "3", "1" };

实际数据可以是任何内容,但列表的长度始终相同。我想将它们合并成一个 List<DTQ> .

public struct DTQ
{
DateTime dt;
double q;
public DTQ(DateTime dt, double q) { this.dt = dt; this.q = q; }
}

有没有办法用 lambda 函数做到这一点?到目前为止,我已经设法创建了一个 lambda 函数,它描述了如果它是三个 strings 我将如何映射数据。而不是 List<string>小号:

Func<string, string, string, DTQ> mergeFields = (d, t, q)
=> new DTQ(DateTime.ParseExact(string.Format("{0}{1}", d, t), "yyyyMMddhhmm", CultureInfo.InvariantCulture), double.Parse(q));

不过,我不确定我可以从那里去哪里。想法是将此函数应用于列表的每个索引。

最佳答案

看起来像是 Zip 的工作, 除了你有 3 个列表而不是 2 个。

使用您当前对 mergeFields 的定义,您可以执行类似的操作:

var dateAndTimes = dates.Zip(times, (d, t) => new { Date = d, Time = t });
var all = dateAndTimes.Zip(quantities, (dt, q) => new { dt.Date, dt.Time, Quantity = q });
var result = all.Select(x => mergeFields(x.Date, x.Time, x.Quantity)).ToList();

如果您想要一个更通用的解决方案,您还可以创建一个包含 3 个集合的 Zip 重载:

public static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
IEnumerable<TThird> third,
Func<TFirst, TSecond, TThird, TResult> resultSelector)
{
return first.Zip(second, (f, s) => new { f, s })
.Zip(third, (fs, t) => resultSelector(fs.f, fs.s, t));
}

(或者,您可以使用 Romoku 的实现,这可能会更快一些)

然后像这样使用它:

var result = dates.Zip(times, quantities, mergeFields).ToList();

关于c# - 使用 lambda 函数合并包含不同对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15908845/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com