cast IEnumerable<T> To Dictionary<int,T>

cast ienumerable to list
linq cast list to another type
c# cast
c# linq cast list
linq cast string to int
convert string to ienumerable<string c#
ienumerable linq query c#
linq select

I have a method with this return type :


I want to map this Method and fill in a Dictionary. Expected result is: Dictionary<int, T>

Dictionary<int, LeaveTypeDto> leaveType = new Dictionary<int, LeaveTypeDto>();
LeaveType.GetList(string.Empty).ToDictionary<int, LeaveTypeDto>();

How can I do this?

Note: GetList return type is IEnumerable of LeaveType, and some fields bust be map in LeaveTypeDto and some fields in LeaveType:


ID is unique and must be use as key in my dictionary, and other field must be map to LeaveTypeDto.

You can specify the key, or the key and value, to take from an enumerable.

If I have a class like so:

public class MyClass
    public int Id {get;set;}
    public string Name {get;set;}

I can write the following to get a Dictionary<int, MyClass>:

IEnumerable<MyClass> values;
IDictionary<int, MyClass> valueDict = values.ToDictionary(t => t.Id);

or the following to get a Dictionary<int, string>:

IEnumerable<MyClass> values;
IDictionary<int, string> valueDict = values.ToDictionary(t => t.Id, t => t.Name);

Cast - Using C# LINQ - A Practical Overview, The feature you want is called covariance, and C# supports it on IEnumerable<T > only when the type arguments are both reference types. Cast an IEnumerable to an IEnumerable (T) Introduction. It's possible to use LINQ queries to get data from an IEnumerable<T>. But for an IEnumerable, you can't Cast an IEnumerable to an IEnumerable<T>. Now, you can use a LINQ query for casted. Points of Interest. There're many collection

I Defined an Extention Method On LeaveType :

public static DTO.LeaveTypeDto ToDto(this DataModel.Timekeeper.LeaveType leaveType)
            return new DTO.LeaveTypeDto
                ID = leaveType.ID,
                Code = leaveType.Code,
                Title = leaveType.Title,
                DailyAvailable = leaveType.DailyAvailable,
                HourlyAvailable = leaveType.HourlyAvailable,
                ShiftBaseAvailable = leaveType.ShiftBaseAvailable,
                PredefinedRemaining = leaveType.PredefinedRemaining,
                Active = leaveType.Active,
                StandardLeaveType = leaveType.StandardLeaveType,
                NotRequestAutomaticaly = leaveType.NotRequestAutomaticaly,
                TemplateFileID = leaveType.TemplateFileID,
                ObligateChooseSubstituteForDailyLeave = leaveType.ObligateChooseSubstituteForDailyLeave,
                ObligateChooseSubstituteForHourlyLeave = leaveType.ObligateChooseSubstituteForHourlyLeave,
                ObligateChooseSubstituteForShiftBaseLeave = leaveType.ObligateChooseSubstituteForShiftBaseLeave,
                ObligateChooseInsertAttachment = leaveType.ObligateChooseInsertAttachment,
                CheckSubstituteLimit = leaveType.CheckSubstituteLimit,
                AbsenceRespiteYearXferLimitDays = leaveType.AbsenceRespiteYearXferLimitDays,
                AbsenceRespiteYearXferMode = leaveType.AbsenceRespiteYearXferMode,
                AbsenceRespiteYearXferValuesSummarize = leaveType.AbsenceRespiteYearXferValuesSummarize,
                DailyRequestRegisterRespite = leaveType.DailyRequestRegisterRespite,
                DayMaxHourlyMinutes = leaveType.DayMaxHourlyMinutes,
                DayWorkMinutes = leaveType.WorkingPeriodMaxHourlyMinutes,
                DecreaseAllOnNXOverflow = leaveType.DecreaseAllOnNXOverflow,
                DecreaseBasedOnMonthWorkingDays = leaveType.DecreaseBasedOnMonthWorkingDays,
                DecreaseDayWorkMinutesOnExtraWorkDays = leaveType.DecreaseDayWorkMinutesOnExtraWorkDays,
                DecreaseOnExtraWorkDays = leaveType.DecreaseOnExtraWorkDays,
                DecreaseOnHolidays = leaveType.DecreaseOnHolidays,
                YearXferValuesSummarize = leaveType.YearXferValuesSummarize,
                MaxContinuousDaysLimit = leaveType.MaxContinuousDaysLimit,
                HourlyRequestRegisterRespite = leaveType.HourlyRequestRegisterRespite,
                YearXferMode = leaveType.YearXferMode,
                MonthlyDaysLimit = leaveType.MonthlyDaysLimit,
                MonthlyXMinsLimit = leaveType.MonthlyXMinsLimit,
                YearXferLimitDays = leaveType.YearXferLimitDays,
                YearLimitDays = leaveType.YearLimitDays,
                MonthStorable = leaveType.MonthStorable,
                YearHourlyMinsLimit = leaveType.YearHourlyMinsLimit,
                MonthPreusable = leaveType.MonthPreusable,
                MonthlyNXMinsLimit = leaveType.MonthlyNXMinsLimit,
                MonthMaxHourlyMinutes = leaveType.MonthMaxHourlyMinutes,
                IncreaseAbsenceRespiteRemaining = leaveType.IncreaseAbsenceRespiteRemaining,
                DailyLeaveRequestCountPerMonthForOthers = leaveType.DailyLeaveRequestCountPerMonthForOthers,
                DailyLeaveRequestDurationPerMonthForOthers = leaveType.DailyLeaveRequestDurationPerMonthForOthers,
                ShiftLeaveRequestCountPerMonthForOthers = leaveType.ShiftLeaveRequestCountPerMonthForOthers,
                ShiftLeaveRequestDurationPerMonthForOthers = leaveType.ShiftLeaveRequestDurationPerMonthForOthers,
                HourlyLeaveRequestCountPerMonthForOthers = leaveType.HourlyLeaveRequestCountPerMonthForOthers,
                UseLeaveRequetLimitForOthersPerMonth = leaveType.UseLeaveRequetLimitForOthersPerMonth,
                DailyCountPerMonth = leaveType.DailyCountPerMonth,
                CheckMeritRemainingInUnpayedRequest = leaveType.CheckMeritRemainingInUnpayedRequest,
                DayMinHourlyMinutes = leaveType.DayMinHourlyMinutes,
                FirstPresenceRangeHourlyCountPerMonth = leaveType.FirstPresenceRangeHourlyCountPerMonth,
                FirstPresenceRangeLenght = leaveType.FirstPresenceRangeLenght,
                FirstPresenceRangeMaxHourlyLimit = leaveType.FirstPresenceRangeMaxHourlyLimit,
                FirstPresenceRangeMinHourlyLimit= leaveType.FirstPresenceRangeMinHourlyLimit,
                HourlyCountPerMonth = leaveType.HourlyCountPerMonth,
                HourlyLeaveRequestDurationPerMonthForOthers = leaveType.HourlyLeaveRequestDurationPerMonthForOthers,
                IsMonthMaxHourlyStorableToCurrent = leaveType.IsMonthMaxHourlyStorableToCurrent,
                LastPresenceRangeHourlyCountPerMonth = leaveType.LastPresenceRangeHourlyCountPerMonth,
                LastPresenceRangeLenght = leaveType.LastPresenceRangeLenght,
                LastPresenceRangeMaxHourlyLimit = leaveType.LastPresenceRangeMaxHourlyLimit,
                LastPresenceRangeMinHourlyLimit = leaveType.LastPresenceRangeMinHourlyLimit,
                MiddlePresenceRangeHourlyCountPerMonth = leaveType.MiddlePresenceRangeHourlyCountPerMonth,
                MiddlePresenceRangeMaxHourlyLimit = leaveType.MiddlePresenceRangeMaxHourlyLimit,
                MiddlePresenceRangeMinHourlyLimit = leaveType.MiddlePresenceRangeMinHourlyLimit,

and by this Line My problem Solved.:)

GetList(string.Empty).ToDictionary(lt => lt.ID, lt => lt.ToDto())

How can I cast IEnumerable<?> to IEnumerable<string>?, IEnumerable'. 'Where' not found. Consider explicitly specifying the type of the range variable 'i'. In this tip, I tell you how to cast an IEnumerable  Cast<TResult>(IEnumerable) Casts the elements of an IEnumerable to the specified type. OfType<TResult>(IEnumerable) Filters the elements of an IEnumerable based on a specified type. AsParallel(IEnumerable) Enables parallelization of a query. AsQueryable(IEnumerable) Converts an IEnumerable to an IQueryable.

If ID is part of LeaveTypeDto

var q = GetList(string.Empty).ToDictionary(b => b.ID);

else use the select overload to get index and then use ToDictionary()

var q = GetList(string.Empty).Select((element, index) => new { i= index, e = element }).ToDictionary(b => b.i, b => b.e);

Cast an IEnumerable to an IEnumerable(T), If you look at the signature, you'll see that the Cast<TResult>() extension method actually extends the older, object-based IEnumerable interface  Cast<TResult>(IEnumerable): The non-generic collection of the IEnumerable interface is converted to the specified type mentioned. OfType<TResult>(IEnumerable): The elements of the IEnumerable are filtered based on the type mentioned. AsParallel(IEnumerable): This is used to enable the running of parallel queries.

What about System.Linq

GetList(string.Empty).ToDictionary(k => int.Parse(k.ID))

Note, the previous example is valid if ID is string, if it is int then even simpler

GetList(string.Empty).ToDictionary(k => k.ID)

C#/.NET Little Wonders: Use Cast() and OfType() to Change , In this post, I investigate the cost of casting to implementations, interfaces, generic interfaces, covariant interfaces, and contravariant interfaces. I  'IEnumerable' does not contain a definition for 'ToList' you're probably missing the System.Linq namespace , because the ToList() method is an extension method provided by that namespace, it's not a member of the IEnumerable interface itself.

Casting to IEnumerable<T> is Two Orders of Magnitude Slower, Following is the syntax of using LINQ Cast() operator to convert items in the collection to another type of new collection. C# Code. IEnumerable<string> result   The Cast<U> () method casts each element of a source IEnumerable<T> sequence, individually, to a base or derived type U and returns a sequence containing all of the resultant elements. NOTE: If the source type T can't be cast to the result type U then the cast will fail with an InvalidCastException.

LINQ Cast() Method, An IEnumerable inside an object[] doesn't cast to/match IEnumerable when iterating each object. But both List and int[] cast properly to  Here we use IEnumerable as the return value of a query expression. We use it with foreach-loops, and also call extension methods on it. Part A: An IEnumerable is returned from a query expression. A query that selects ints will be of type IEnumerable<int>. Part B: On an IEnumerable variable, we can use the foreach-loop. This loop iterates with

IEnumerable inside an object[] doesn't cast to IEnumerable · Issue , // runtime-in-c-sharp. 32. public static IEnumerable Cast(this IEnumerable self, Type  IEnumerable myEnumerable = (IEnumerable)patients; IEnumerable<string> myGenericEnumerable = (IEnumerable<string>)patients; //Need to assign inenumerable to listview but cast exception occurs PatientsListView.ItemsSource = myGenericEnumerable; In which method? That method has to be async. Can you paste whole .cs file with this code?