C# 从 Linq 中的列表中选择多个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1202981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:47:37  来源:igfitidea点击:

Select Multiple Fields from List in Linq

c#linqdata-structures

提问by Chet

In ASP.NET C# I have a struct:

在 ASP.NET C# 中,我有一个结构:

public struct Data
{
    public int item1;
    public int item2;
    public int category_id;
    public string category_name;
}

and I have a List of those. I want to select category_idand category_name, running a DISTINCTand finally an ORDERBYon category_name.

我有一个清单。我想选择category_idand category_name,运行一个DISTINCT,最后一个ORDERBYon category_name

Here's what I have now:

这是我现在所拥有的:

List<Data> listObject = getData();
string[] catNames = listObject
                    .Select(i=> i.category_name)
                    .Distinct()
                    .OrderByDescending(s => s)
                    .ToArray();

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[])?

这显然只是获取类别名称。我的问题是,我如何获得多个字段,以及我将把它存储在什么数据结构中(不是 a string[])?

EDIT

编辑

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.

使用结构列表并不是一成不变的。如果建议更改我的支持数据结构以使选择更容易(我将编写很多这样的内容),那么我很乐意接受建议。

采纳答案by Jason

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();

Since you (apparently) need to store it for later use, you could use the GroupBy operator:

由于您(显然)需要存储它以备后用,您可以使用 GroupBy 运算符:

Data[] cats = listObject
    .GroupBy(i => new { i.category_id, i.category_name })
    .OrderByDescending(g => g.Key.category_name)
    .Select(g => g.First())
    .ToArray();

回答by Mehrdad Afshari

You could use an anonymous type:

您可以使用匿名类型:

.Select(i => new { i.name, i.category_name })

The compiler will generate the code for a class with nameand category_nameproperties and returns instances of that class. You can also manually specify property names:

编译器将为具有namecategory_name属性的类生成代码并返回该类的实例。您还可以手动指定属性名称:

i => new { Id = i.category_id, Name = i.category_name }

You can have arbitrary number of properties.

您可以拥有任意数量的属性。

回答by Paul van Brenk

var result = listObject.Select( i => new{ i.category_name, i.category_id } )

This uses anonymous types so you must the var keyword, since the resulting type of the expression is not known in advance.

这使用匿名类型,因此您必须使用 var 关键字,因为事先不知道表达式的结果类型。

回答by Noldorin

This is task for which anonymous typesare very well suited. You can return objects of a type that is created automatically by the compiler, inferred from usage.

这是匿名类型非常适合的任务。您可以返回由编译器自动创建的类型的对象,从用法推断。

The syntax is of this form:

语法是这种形式:

new { Property1 = value1, Property2 = value2, ... }

For your case, try something like the following:

对于您的情况,请尝试以下操作:

var listObject = getData();
var catNames = listObject.Select(i =>
    new { CatName = i.category_name, Item1 = i.item1, Item2 = i.item2 })
    .Distinct().OrderByDescending(s => s).ToArray();

回答by IRBMe

var selectedCategories =
    from value in
        (from data in listObject
        orderby data.category_name descending
        select new { ID = data.category_id, Name = data.category_name })
    group value by value.Name into g
    select g.First();

foreach (var category in selectedCategories) Console.WriteLine(category);

Edit: Made it more LINQ-ey!

编辑:让它更加 LINQ-ey!

回答by Joe Chung

(from i in list
 select new { i.category_id, i.category_name })
 .Distinct()
 .OrderBy(i => i.category_name);

回答by AR M

You can select multiple fields using linq Select as shown above in various examples this will return as an Anonymous Type. If you want to avoid this anonymous type here is the simple trick.

您可以使用 linq Select 选择多个字段,如上面的各种示例所示,这将作为匿名类型返回。如果你想避免这种匿名类型,这里有一个简单的技巧。

var items = listObject.Select(f => new List<int>() { f.Item1, f.Item2 }).SelectMany(item => item).Distinct();

I think this solves your problem

我认为这可以解决您的问题

回答by Victor

You can make it a KeyValuePair, so it will return a "IEnumerable<KeyValuePair<string, string>>"

您可以将其设为 KeyValuePair,因此它将返回一个 "IEnumerable<KeyValuePair<string, string>>"

So, it will be like this:

所以,它会是这样的:

.Select(i => new KeyValuePair<string, string>(i.category_id, i.category_name )).Distinct();

回答by Zoyeb Shaikh

public class Student
{
    public string Name { set; get; }
    public int ID { set; get; }
}

class Program
{
  static void Main(string[] args)
    {
        Student[] students =
        {
        new Student { Name="zoyeb" , ID=1},
        new Student { Name="Siddiq" , ID=2},
        new Student { Name="sam" , ID=3},
        new Student { Name="james" , ID=4},
        new Student { Name="sonia" , ID=5}
        };

        var studentCollection = from s in students select new { s.ID , s.Name};

        foreach (var student in studentCollection)
        {
            Console.WriteLine(student.Name);
            Console.WriteLine(student.ID);
        }
    }
}