简体   繁体   中英

Converting types in c#

Is there a better way to write this without the foreach? I want to add items (Jurisdictions) from the IEnumerable of type int and convert into an IList which contains the property Ref and should be set in there.

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

You can express the same logic using LINQ, but in this case I don't think it's easier to read. Performance ought to be about the same.

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

You mean

using System.Linq;
...
Jurisdictions = Firms.ToList();

or

Jurisdictions = firmRef.Select(x => new TrackFilterGenericRef { Ref = x, Type = ContentTypes.Firm, Description = "" }).ToList();

?

In the first example, you would get a list with the same instances as in the Firms enumerable. In the second you would get a list with new instances in the Jurisdictions list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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