C# Groupby Linq 和 foreach

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12873855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:46:38  来源:igfitidea点击:

C# Groupby Linq and foreach

c#linq

提问by IEnumerable

I need a more efficient way of producing multiple files from my data group. Im using a List<MyObject>type and my object has some public properties in which I need to group the data by.

我需要一种更有效的方法来从我的数据组中生成多个文件。我使用一种List<MyObject>类型,我的对象有一些公共属性,我需要在其中对数据进行分组。

I have heard of Linqand it sounds like something I could use. However Im not sure how to go about it.

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

I need to produce a text file for each STATE, so grouping all the MyObjects(people) by state, then running a foreachlook on them to build the TEXT file.

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

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. 

In total for the above data I need 3 files;

对于上述数据,我总共需要 3 个文件;

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

采纳答案by lesscode

Something like this, perhaps?

像这样的东西,也许?

    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);
            }
        }
    }

回答by iamkrillin

You def. could use LINQ here.

你确定。可以在这里使用 LINQ。

lst.GroupBy(r=> r.state).ToList().ForEach(r=> {
        //state= r.Key
        //

        foreach (var v in r)
        {

        }
    });

The thing about linq. If you want to know how to do something in it. Think "how would I do this in SQL". The keywords are for the most part the same.

关于 linq 的事情。如果您想知道如何在其中做某事。想想“我将如何在 SQL 中做到这一点”。关键字大部分是相同的。

回答by user568021

Something like...

就像是...

string builderNsw = "";
foreach (MyObject item in lst.Where(o=>o.state == 'nsw'))  {

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

}

...but there are probably many ways to achieve this.

...但可能有很多方法可以实现这一目标。

回答by k.m

You can actually produce entire content with LINQ:

您实际上可以使用 LINQ 生成整个内容:

var entryFormat = "{1}{0}{2}{0}{0}{0}";
var groupsToPrint = lst
   .GroupBy(p => p.state)
   .Select(g => new 
    {
       State = g.Key,
       // produce file content on-the-fly from group entries
       Content = string.Join("", g.Select(v => string.Format(entryFormat, 
           Environment.NewLine, v.name, v.url)))
    });

var fileNameFormat = "{0}.txt";
foreach (var entry in groupsToPrint)
{
    var fileName = string.Format(fileNameFormat, entry.State);
    File.WriteAllText(fileName, entry.Content);
}

回答by Arun Prasad E S

Same as Above - Iterating through groups by group, can get group name also

同上 - 按组遍历组,也可以获得组名

    int itemCounter = 1;
    IEnumerable<DataRow> sequence = Datatables.AsEnumerable();

    var GroupedData = from d in sequence group d by d["panelName"];      // GroupedData is now of type IEnumerable<IGrouping<int, Document>>

    foreach (var GroupList in GroupedData) // GroupList = "document group", of type IGrouping<int, Document>
    {          
      bool chk = false;
      foreach (var Item in GroupList)
      {

        if (chk == false) // means when header is not inserted
        {
          var groupName = "Panel Name : " + Item["panelName"].ToString();

          chk = true;
        }
        var count = itemCounter.ToString();
        var itemRef = Item["reference"].ToString();

        itemCounter++;
      }
    }