从 Linq 列表中选择多个字段 [英] Select Multiple Fields from List in Linq

查看:44
本文介绍了从 Linq 列表中选择多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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_idcategory_name,在 category_nameDISTINCT 和最后一个 ORDERBY代码>.

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.

推荐答案

匿名类型允许您将任意字段选择到稍后在代码中强类型的数据结构中:

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 列表中选择多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆