【问题标题】:Reuse select new object in linq statement在 linq 语句中重用选择新对象
【发布时间】:2019-11-07 13:36:02
【问题描述】:

下面是我的 linq 代码,它可以工作。我的问题是如何在函数中“重用”那些新的 ContactResponse 和新的 AddressResponse 以在另一个查询中重用它?

var queryset = (
            from a in _repoWrapper.Workshop.FindAll()
            where (a.IsActive == true && a.Entity.EntityType.Code == Global.EntityTypeServiceCenterCode)
            select new ServiceCenterResponse
            {
                Id = a.Id,
                Name = a.Name,
                EntityId = a.EntityId,
                Contacts = a.WorkshopContacts.Select(p => new ContactResponse
                {
                    Id = p.Contact.Id,
                    Type = p.Contact.ContactType.Description,
                    Code = p.Contact.ContactType.Code,
                    Value = p.Contact.Value
                }).ToList(),
                Addresses = a.WorkshopAddresses.Select(p => new AddressResponse
                {
                    Id = p.Address.Id,
                    AddressType = p.Address.AddressType.Code,
                    StreetLine1 = p.Address.StreetLine1,
                    StreetLine2 = p.Address.StreetLine2,
                    City = p.Address.City,
                    State = p.Address.State,
                    PostCode = p.Address.PostCode,
                    Country = p.Address.Country,
                    Longitude = p.Address.Longitude,
                    Latitude = p.Address.Latitude,
                    Others = p.Address.Others
                }).ToList()
            }
        );

【问题讨论】:

  • 您能举个例子说明您将如何使用这些可重新密封的查询吗?
  • 创建一个方法,比如 CreateContactResponse,它接受一个 WorkshopContact 参数并返回一个 ContactResponse 对象,并使用类似a.WorkshopContacts.Select(p => CreateContactResponse(p)).ToList()的方法

标签: c# linq asp.net-core


【解决方案1】:

如果我正确理解你的问题,那么试试这个:

 Func<WorkshopContact, ContactResponse> contactResponseProjection= p => new ContactResponse
 {
   Id = p.Contact.Id,
   Type = p.Contact.ContactType.Description,
   Code = p.Contact.ContactType.Code,
   Value = p.Contact.Value
 };

并使用:

...
  Contacts = a.WorkshopContacts.Select(contactResponseProjection).ToList(),
...

【讨论】:

    【解决方案2】:

    Linq 在 Select 方法中有一个 Func 类型的参数。这意味着您可以将方法传递给它。 让我试着做一个例子。

    List<int> list = new List<int> { 1, 2, 3 };
    list.Select(AddOne);
    

    其中AddOne 是一个可以声明的方法,并且必须有一个int 类型的参数和一个你想要返回的返回值。例如。

    public int AddOne(int value)
    {
        return value + 1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2012-01-12
      • 1970-01-01
      • 2013-12-27
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多