简体   繁体   English

查询Linq返回列表 <int> 从对象

[英]Query Linq return List<int> from object

I have this class : 我有这个课:

public class MyClass
{
    public int Id { get; set; }
    public int MyId1 { get; set; }
    public int MyId2 { get; set; }
    public int MyId3 { get; set; }
    public string MyName { get; set; }
}

I have a List<MyClass> 我有一个List<MyClass>

I do a query : 我查询:

var result = (from my in MyClass
             where Id == 5
             select my).First();

I'd like in result a List with MyId1, MyId2 and MyId3 我想要的结果是带有MyId1,MyId2和MyId3的列表

Any idea ? 任何想法 ?

Thanks, 谢谢,

var result = (from my in list
             where my.Id == 5
             select new List<int>() { my.MyId1, my.MyId2, my.MyId3 }).First();

I think there is two steps in your code: (1) obtaining required object and (2) convert that object to list. 我认为您的代码中有两个步骤:(1)获取所需的对象,(2)将对象转换为列表。 So actually I think more appropriate would be something like this: 所以实际上我认为更合适的是这样的:

var firstResult = list.First(my => my.Id == 5);
var result = new List<int>{firstResult.MyId1, my.MyId2, my.MyId3};

This approach is more slightly better because it simpler and states you intention more clear. 这种方法稍微好一点,因为它更简单,并且表明您的意图更加明确。

Consider Single Responsibility Principle : your code should have only one reason to change. 考虑单一责任原则 :您的代码应该只有一个更改理由。 Your code (and Arsen's code as well) lacks of this ability. 您的代码(以及Arsen的代码)缺乏此功能。 When requirements changed and you'll need to change your class or add additional property to the list you'll need to change your filtering logic. 当需求更改时,您需要更改您的类或向列表中添加其他属性,您需要更改过滤逻辑。 But its clear that those two aspects are orthogonal and should not changed in such circumstances. 但是很明显,这两个方面是正交的,在这种情况下不应更改。

BTW you can add extension method or simple method to your class MyClass that will convert it to List. 顺便说一句,您可以在类MyClass中添加扩展方法或简单方法,将其转换为List。 In this case your code would be even more readable: 在这种情况下,您的代码将更具可读性:

var result = list.First(my => my.Id == 5).ToListOfInt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM