gpt4 book ai didi

C# Groupby Linq 和 foreach

转载 作者:IT王子 更新时间:2023-10-29 04:29:02 24 4
gpt4 key购买 nike

我需要一种更有效的方法来从我的数据组中生成多个文件。我正在使用 List<MyObject> type 并且我的对象有一些公共(public)属性,我需要根据这些属性对数据进行分组。

我听说过 Linq,它听起来像是我可以使用的东西。但是我不确定如何去做。

我需要为每个 STATE 生成一个文本文件,因此将所有 MyObjects 分组(人)按州,然后运行 ​​foreach查看它们以构建 TEXT 文件。

void Main()
{

List<MyObject> lst = new List<MyObject>();
lst.Add(new MyObject{ name = "bill", state = "nsw", url = "microsoft.com"});
lst.Add(new MyObject{ name = "ted", state = "vic", url = "apple.com"});
lst.Add(new MyObject{ name = "jesse", state = "nsw", url = "google.com"});
lst.Add(new MyObject{ name = "james", state = "qld", url = "toshiba.com"});

string builder = "";
foreach (MyObject item in myObjects) {

builder += item.name + "\r\n";
builder += item.url + "\r\n" + "\r\n\r\n";

}

and out to the `StreamWriter` will be the filenames by state.

以上数据总共需要3个文件;

-nsw.txt
-vic.txt
-qld.txt

最佳答案

也许是这样的?

    var groups = lst.GroupBy(x => x.state);

foreach (var group in groups)
{
using (var f = new StreamWriter(group.Key + ".txt"))
{
foreach (var item in group)
{
f.WriteLine(item.name);
f.WriteLine(item.url);
}
}
}

关于C# Groupby Linq 和 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12873855/

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