用Linq 解决 数据的多字段分组统计(VB.net)

Sub Main
	dim objs as array = { _ 
		new with { .Item="A",  .Loc="L1", .Q1 = 1, .Q2=0}, _
		new with { .Item="A",  .Loc="L1", .Q1 = 2, .Q2=1}, _
		new with { .Item="B",  .Loc="L1", .Q1 = 3, .Q2=99}, _
		new with { .Item="B",  .Loc="L2", .Q1 = 7, .Q2=0} _
		}
		
		dim query as IEnumerable = from e in objs 
		group e by key= new with { key e.Item, key e.Loc }  into g=Group _
		select new with { _
			.key = key.toString, _
			.value = new with { _
				.Q1 = g.sum(function(x) x.Q1), _
				.Q2 = g.sum(function(x) x.Q2), _
				.Count = g.Count _
			} _
		}
		
		dim objHash as new HashTable 
		for each e as object in query
			objHash.Add(e.Key,e.Value)
			Console.WriteLine(e)
		next 
		
		dim obj as Object = objHash("{ Item = B, Loc = L1 }")
		Console.WriteLine("  | Q1:{0}- Q2:{1}-Q3:{2} |", obj.Q1, obj.Q2, obj.Count,5)
		
		for each e as object in objs
			Console.WriteLine("{0}-{1}-{2}", e.Item, e.Q1,e.Q2)
		next
End Sub


LinqPad  测试结果:


5VB$AnonymousType_3>4

{ key = { Item = A, Loc = L1 }, value = { Q1 = 3, Q2 = 1, Count = 2 } }

key

{ Item = A, Loc = L1 }

value

5VB$AnonymousType_44

{ Q1 = 3, Q2 = 1, Count = 2 }

Q1

3

Q2

1

Count

2

5VB$AnonymousType_3>4

{ key = { Item = B, Loc = L1 }, value = { Q1 = 3, Q2 = 99, Count = 1 } }

key

{ Item = B, Loc = L1 }

value

5VB$AnonymousType_44

{ Q1 = 3, Q2 = 99, Count = 1 }

Q1

3

Q2

99

Count

1

 

5VB$AnonymousType_3>4

{ key = { Item = B, Loc = L2 }, value = { Q1 = 7, Q2 = 0, Count = 1 } }

key

{ Item = B, Loc = L2 }

value

5VB$AnonymousType_44

{ Q1 = 7, Q2 = 0, Count = 1 }

Q1

7

Q2

0

Count

1


  | Q1:3- Q2:99-Q3:1 |
A-1-0
A-2-1
B-3-99
B-7-0

你可能感兴趣的:(VB.NET)