在没有foreach的情况下,有没有更好的方法来编写此代码? 我想从类型为int的IEnumerable中添加项目(管辖区),并将其转换为包含属性Ref的IList,应在此处进行设置。
public class TrackDataFilter
{
public TrackDataFilter(IEnumerable<int> firmRef, int? superSectorRef, DateTime from, DateTime to, int userFirmRef) : this()
{
Firms = firmRef.Select(x => new TrackFilterGenericRef { Ref = x, Type = ContentTypes.Firm, Description = "" });
SuperSectorRef = superSectorRef;
From = from;
To = to;
UserFirmRef = userFirmRef;
}
public TrackDataFilter()
{
Workareas = new List<TrackFilterGenericRef>();
Jurisdictions = new List<TrackFilterGenericRef>();
Tags = new List<TrackFilterGenericRef>();
Firms = Enumerable.Empty<TrackFilterGenericRef>();
}
public IList<TrackFilterGenericRef> Jurisdictions { get; set; }
...
}
public class TaxiBriefingFilter
{
public IEnumerable<int> Jurisdictions { get; set; }
...
}
// add items in IEnumerable<int> Jurisdictions into IList<TrackFilterGenericRef>
var filter = new TaxiBriefingFilter();
var dataFilter = new TrackDataFilter(new int[] { companyId }, null, from, to, userFirmRef);
foreach (var jurisdictionRef in filter.Jurisdictions)
{
dataFilter.Jurisdictions.Add(new TrackFilterGenericRef { Ref = jurisdictionRef});
}
var jurisdictions = trackAnalyticsService.GetJurisdictions(dataFilter, maxJurisdictions);
...
答案 0 :(得分:1)
您可以使用LINQ表达相同的逻辑,但是在这种情况下,我认为它不容易阅读。性能应该差不多。
using System.Linq;
...
var filter = new TaxiBriefingFilter();
var dataFilter = new TrackDataFilter(new int[] { companyId }, null, from, to, userFirmRef);
dataFilter.Jurisdictions.AddRange(
filter.Jurisdictions.Select(jref => new TrackFilterGenericRef { Ref = jref }));
答案 1 :(得分:0)
你是说
using System.Linq;
...
Jurisdictions = Firms.ToList();
或
Jurisdictions = firmRef.Select(x => new TrackFilterGenericRef { Ref = x, Type = ContentTypes.Firm, Description = "" }).ToList();
?
在第一个示例中,您将获得一个列表,该列表具有与Firms
枚举中相同的实例。
在第二秒中,您将在Jurisdictions
列表中获得一个包含新实例的列表。