IEnumerable
IEnumerable

Reputation: 3790

C# Groupby Linq and foreach

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.

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

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

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;

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

Upvotes: 37

Views: 90422

Answers (5)

Arun Prasad E S
Arun Prasad E S

Reputation: 10125

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

Upvotes: 1

lesscode
lesscode

Reputation: 6361

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

Upvotes: 70

k.m
k.m

Reputation: 31464

You can actually produce entire content with 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);
}

Upvotes: 4

user568021
user568021

Reputation: 1476

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.

Upvotes: 1

iamkrillin
iamkrillin

Reputation: 6876

You def. could use LINQ here.

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.

Upvotes: 17

Related Questions