我有一份包含以下内容的文件:
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名称
答案 0 :(得分: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() });
答案 1 :(得分: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" }
});
第3步:在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());