-2

我有一个包含以下内容的文档:

    1> Id: "10204"; FromCity:"Vadodara"; ToCity:"Surat"; OfficeId:{"office1","Office2","Office3"} // row-1
    2> Id: "10205"; FromCity:"Ahmedabad"; ToCity:"Surat"; OfficeId:{"office2","Office3","Office4"} // row-2

那么我的输出应该是:

    office1 - 1;
    Office2 - 2;
    Office3 - 2;
    Office4 - 1;

请使用 LINQ 帮助我解决这个问题。我已经拆分了 Array 及其单个文档的单个计数。

var OfficeID = results2
                .GroupBy(frm => new { frm.ItemNumber },
                (key, group) => new
                {
                    Key1 = key.ItemNumber,
                    Count = group.Sum(e => e.Count)
                });

在此先感谢我这样做了:

        var OfficeId= results2.SelectMany(@class => @class.ItemNumber)
            .GroupBy(s => s).Select(a => new { officeId = a, count = a.Count() });


        foreach (var i in OfficeId)
        {
            Console.WriteLine(i.officeId+"\t"+i.count);
        }

但我没有在循环中显示 OfficeId 名称

4

2 回答 2

1

试试这个方法。

class MyClass
{
    public int id { get; set; }
    public string[] officeId { get; set; }
}

var objects = new List<MyClass>
                  {
                      new MyClass{id=1, officeId=new[]{"office1","Office2","Office3"}},
                      new MyClass {id=2,officeId=new[]{"office1","Office2","Office3"}},
                      new MyClass{id=3, officeId=new[]{"office1","Office2","Office3"}}
                  };


var enumerable = objects.SelectMany(@class => @class.officeId).GroupBy(s => s).Select(a => new { officeId = a.Key, count = a.Count() });
于 2013-10-03T11:01:56.600 回答
0

请按照以下步骤操作。

第1 步:创建如下自定义类来保存您的数据。

public class Document
    {
        public int Id { get; set; }
        public string FromCity { get; set; }
        public string ToCity { get; set; }
        public List<string> OfficeIds { get; set; }
    }

Step2:这一步只是填充虚拟数据,你不需要它。

List<Document> documents = new List<Document>();

            //row 1
            documents.Add(new Document()
            {
                Id = 10204,
                FromCity = "Vadodara",
                ToCity = "Surat",
                OfficeIds = new List<string>() { "Office2", "Office2", "Office3" }

            });

            //row 2
            documents.Add(new Document()
            {
                Id = 10205,
                FromCity = "Ahmedabad",
                ToCity = "Surat",
                OfficeIds = new List<string>() { "Office2", "Office3", "Office4" }

            });

Step3:使用 LINQ 中的 SelectMany 转换为 office 字符串值列表。

List<string> lstOffice  = documents.SelectMany(d => d.OfficeIds).ToList();

Step4:使用where子句过滤数据

Console.WriteLine("Office1 " +  lstOffice.Where(s => s.ToLower() == "office1").Count().ToString());
Console.WriteLine("Office2 " +  lstOffice.Where(s => s.ToLower() == "office2").Count().ToString());
Console.WriteLine("Office3 " +  lstOffice.Where(s => s.ToLower() == "office3").Count().ToString());
Console.WriteLine("Office4 " +  lstOffice.Where(s => s.ToLower() == "office4").Count().ToString());
于 2013-10-03T12:20:44.860 回答