我有一个具有以下结构的模型;
{
Name: // .... //,
Id: // ... //,
Tab: "tabName",
// ... other properties ... //
}
是否可以使用此类型的IList<T>
,并通过Tab
属性将项目提取到组中?这样我只能使用LINQ
查询来得到这样的形状?
{
"tabName1": [ item1, item4, item8 ],
"tabName2": [ item2, item5, item9 ],
"tabName3": [ item3, item6, item10]
}
答案 0 :(得分:1)
我假设数据结构是这样的:
var obj = new[] {
new { Name = "ss", Id = 1, Tab = "tabName1" },
new { Name = "ss", Id = 1, Tab = "tabName1" },
new { Name = "ss", Id = 1, Tab = "tabName1" },
new { Name = "ss", Id = 1, Tab = "tabName2" },
new { Name = "ss", Id = 1, Tab = "tabName1" }
};
您可以通过这种方式使用群组:
var query = from s in obj
group s by s.Tab into newGroup
select newGroup;
使用方法语法:
var query = obj.GroupBy(p => p.Tab).Select(p => new { items = p });
答案 1 :(得分:1)
您可以通过GroupBy方法执行此操作。下面我为你设置了一个演示。代码将生成一个列表。该列表中的每个对象都有一个键和一个items属性。键将是tabname,itemsproperty将包含带有项目的列表。
类
class TestObj
{
public int Id { get; set; }
public string Name { get; set; }
public string Tab { get; set; }
}
实施例
List<TestObj> obj = new List<TestObj>()
{
new TestObj() { Id = 1, Tab = "tab1", Name = "name1" },
new TestObj() { Id = 2, Tab = "tab1", Name = "name2" },
new TestObj() { Id = 3, Tab = "tab1", Name = "name3" },
new TestObj() { Id = 4, Tab = "tab2", Name = "name4" },
new TestObj() { Id = 5, Tab = "tab2", Name = "name5" },
new TestObj() { Id = 6, Tab = "tab4", Name = "name6" },
new TestObj() { Id = 7, Tab = "tab3", Name = "name7" },
new TestObj() { Id = 8, Tab = "tab3", Name = "name8" },
new TestObj() { Id = 9, Tab = "tab3", Name = "name9" },
};
var list = obj.GroupBy(x => x.Tab).Select(x => new { key = x.Key, items = x }).ToList();
答案 2 :(得分:0)
尝试这样的事情
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Something> somethings = new List<Something>() {
new Something() { tab = 1},
new Something() { tab = 2},
new Something() { tab = 3},
new Something() { tab = 4},
new Something() { tab = 5},
new Something() { tab = 6},
new Something() { tab = 7},
new Something() { tab = 8},
new Something() { tab = 9}
};
var result = somethings.Take(3).Select((x, i) => somethings.Where((y, ii) => (ii % 3) == i).Select(z => z.tab).ToArray()).ToArray();
}
}
public class Something
{
public int tab { get; set; }
}
}