问题描述
在ASP.NET C#我有一个结构:
In ASP.NET C# I have a struct:
public struct Data
{
public int item1;
public int item2;
public int category_id;
public string category_name;
}
和我的人的名单。我想选择 CATEGORY_ID
和 CATEGORY_NAME
,运行 DISTINCT
最后一个 ORDERBY
在 CATEGORY_NAME
。
and I have a List of those. I want to select category_id
and category_name
, running a DISTINCT
and finally an ORDERBY
on category_name
.
这是我现在有:
List<Data> listObject = getData();
string[] catNames = listObject
.Select(i=> i.category_name)
.Distinct()
.OrderByDescending(s => s)
.ToArray();
这显然只是获取类别名称。我的问题是,我怎么得到多个领域,什么数据结构存储我在这(不是的String []
)?
This obviously just gets the category name. My question is, how do I get multiple fields, and what data structure will I store this in (not a string[]
)?
修改
使用结构的名单不是一成不变的。如果这将是可取改变我的后盾的数据结构,使选择更简单(我会写很多这样的),那么我会乐意接受建议。
Using a list of structs is not set in stone. If it would be advisable to change my backing data structure to make selects easier (I'll be writing a lot of these) then I'd gladly take recommendations.
推荐答案
匿名类型允许您选择任意域到数据结构,有很强的在code类型以后:
Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:
var cats = listObject
.Select(i => new { i.category_id, i.category_name })
.Distinct()
.OrderByDescending(i => i.category_name)
.ToArray();
既然你(显然)需要将其存储供以后使用,您可以使用GROUPBY运算符:
Since you (apparently) need to store it for later use, you could use the GroupBy operator:
Data[] cats = listObject
.GroupBy(i => new { i.category_id, i.category_name })
.OrderByDescending(g => g.Key.category_name)
.Select(g => g.First())
.ToArray();
这篇关于从列表选择Linq中的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!