System.Collections.IEnumerable.Cast()

Here are the examples of the csharp api System.Collections.IEnumerable.Cast() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4572 Examples 7

19 View Source File : AzureKeyVaultCertificateClient.cs
License : MIT License
Project Creator : ActiveLogin

private X509Certificate2 GetX509Certificate2(byte[] certificate)
        {
            var exportedCertCollection = new X509Certificate2Collection();
            exportedCertCollection.Import(certificate, string.Empty, X509KeyStorageFlags.MachineKeySet);

            return exportedCertCollection.Cast<X509Certificate2>().First(x => x.HasPrivateKey);
        }

19 View Source File : RxGeometryGroup.cs
License : MIT License
Project Creator : adospace

protected override IEnumerable<VisualNode> RenderChildren()
        {
            return _internalChildren.Cast<VisualNode>();
        }

19 View Source File : HelperExtensions.cs
License : MIT License
Project Creator : A-Tabeshfard

public static string FormatUsingObject(this string @this, object poObject)
        {
            var sFormatted = @this;

            foreach (var oProperty in TypeDescriptor.GetProperties(poObject).Cast<PropertyDescriptor>())
            {
                sFormatted = sFormatted.Replace("{" + oProperty.Name + "}", oProperty.GetValue(poObject).ToStringOrNull());
            }

            return sFormatted;
        }

19 View Source File : BodyPart.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static List<CoverageMask> GetFlags(CoverageMask coverage)
        {
            return Enum.GetValues(typeof(CoverageMask)).Cast<CoverageMask>().Where(p => p != CoverageMask.Unknown && coverage.HasFlag(p)).ToList();
        }

19 View Source File : CalculaValor.cs
License : MIT License
Project Creator : abrandaol-youtube

public void DefineValor(Pizza pizza)
        {
            var totalIngradientes = Enum.GetValues(typeof(IngredientesType)).Cast<Enum>().Count(pizza.IngredientesType.HasFlag);

            /*
             *  Expressão apra calculo do valor total da pizza
             *
             *  (Total de Ingradientes x R$ 1,70) + ( o tamanho da pizza x R$ 10,00) + (se for doce mais R$ 10,00) +
             *  (Se a borda for de chocolate é o tamanho da borda x R$ 5,00 e se for salgada x R$ 2,00)             
             */
            var valorIngredintes = totalIngradientes * 1.70;
            var valorTamanho = (int)pizza.PizzaSize * 10;
            var valorTipo = pizza.PizzaType == PizzaType.Doce ? 10 : 0;

            var valorBorda = 0;

            if (pizza.Borda != null)
            {
                valorBorda = pizza.Borda.BordaType == BordaType.Chocolate
                    ? (5 * (int)pizza.Borda.BordaSize)
                    : (2 * (int)pizza.Borda.BordaSize);
            }

            pizza.Valor = valorIngredintes + valorTamanho + valorTipo + valorBorda;
        }

19 View Source File : TypeExtensions.cs
License : MIT License
Project Creator : 52ABP

public static T[] GetAttributes<T>(this MemberInfo memberInfo, bool inherit = false) where T : Attribute
        {
            return memberInfo.GetCustomAttributes(typeof (T), inherit).Cast<T>().ToArray();
        }

19 View Source File : KeyboardHookManager.cs
License : MIT License
Project Creator : adainrivers

public Guid RegisterHotkey(ModifierKeys modifiers, int virtualKeyCode, Func<Task> action)
        {
            var allModifiers = Enum.GetValues(typeof(ModifierKeys)).Cast<ModifierKeys>().ToArray();

            // Get the modifiers that were chained with bitwise OR operation as an array of modifiers
            var selectedModifiers = allModifiers.Where(modifier => modifiers.HasFlag(modifier)).ToArray();

            return RegisterHotkey(selectedModifiers, virtualKeyCode, action);
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec

public static Dictionary<string, List<string>> ParseRuleFile(string ruleFilePath)
        {
            Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
            var contents = new StringReader(File.ReadAllText(ruleFilePath));
            string line = contents.ReadLine();
                while (line != null)
                {
                    try
                    {
                        //if the line contains a mitre_technique
                        if (line.Contains("mitre_technique_id "))
                        {
                            List<string> techniques = new List<string>();
                            //get all indexes from all technique ids and add them all to a list
                            IEnumerable<int> indexes = Regex.Matches(line, "mitre_technique_id ").Cast<Match>().Select(m => m.Index + "mitre_technique_id ".Length);
                            foreach (int index in indexes) 
                                techniques.Add(line.Substring(index, line.IndexOfAny(new [] { ',', ';' }, index) - index));
                            int head = line.IndexOf("msg:\"") + "msg:\"".Length;
                            int tail = line.IndexOf("\"", head);
                            string msg = line.Substring(head, tail - head);
                            head = line.IndexOf("sid:") + "sid:".Length;
                            tail = line.IndexOfAny(new char[] { ',', ';' }, head);
                            string sid = line.Substring(head, tail - head);
                            //for each found technique add the sid along with the message to the content
                            foreach( string technique in techniques)
                            {
                                if (res.ContainsKey(technique))
                                    res[technique].Add($"{sid} - {msg}");
                                else
                                    res.Add(technique, new List<string> { $"{sid} - {msg}" });
                            }
                        }
                        line = contents.ReadLine();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(line);
                        Console.WriteLine(e.Message);
                        line = contents.ReadLine();
                }
                }
                return res;
            }

19 View Source File : CrmEntityStore.cs
License : MIT License
Project Creator : Adoxio

protected void MergeRelatedEnreplacedies(ICollection<Enreplacedy> parents, Relationship relationship, string relatedLogicalName, ColumnSet relatedColumns)
		{
			if (parents == null || parents.Count == 0)
			{
				return;
			}

			var parentIds = parents.Select(parent => parent.Id).Cast<object>().ToList();
			var parentIdsCondition = new[] { new Condition { Attribute = PrimaryIdAttribute, Operator = ConditionOperator.In, Values = parentIds } };

			var fetchRelatedEnreplacedies = new Fetch
			{
				Enreplacedy = new FetchEnreplacedy(relatedLogicalName, relatedColumns.Columns)
				{
					Filters = new[] { new Filter {
						Conditions = GetActiveStateConditions().Concat(parentIdsCondition).ToList()
					} }
				}
			};

			var relatedEnreplacedies = Context.Service.RetrieveMultiple(fetchRelatedEnreplacedies);

			foreach (var parent in parents)
			{
				var parentId = parent.ToEnreplacedyReference();
				var relatedSubset = relatedEnreplacedies.Enreplacedies.Where(binding => Equals(binding.GetAttributeValue<EnreplacedyReference>(PrimaryIdAttribute), parentId));
				parent.RelatedEnreplacedies[relationship] = new EnreplacedyCollection(relatedSubset.ToList());
			}
		}

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<long> LastChanceToFindNotAlreadyProvidedLong(ref long? minValue, ref long? maxValue, SortedSet<object> alreadyProvidedValues, IFuzz fuzzer)
        {
            minValue = minValue ?? long.MinValue;
            maxValue = maxValue ?? long.MaxValue;

            var allPossibleValues = GenerateAllPossibleOptions(minValue.Value, maxValue.Value);
            
            var remainingCandidates = allPossibleValues.Except<long>(alreadyProvidedValues.Cast<long>()).ToArray();
            
            if (remainingCandidates.Any())
            {
                var index = fuzzer.GenerateInteger(0, remainingCandidates.Length - 1);
                var randomRemainingNumber = remainingCandidates[index];

                return new Maybe<long>(randomRemainingNumber);
            }

            return new Maybe<long>();
        }

19 View Source File : ConcurrentList.cs
License : MIT License
Project Creator : Accelerider

public IEnumerator<T> GetEnumerator()
        {
            lock (_storage)
            {
                var temp = new T[_storage.Count];
                _storage.CopyTo(temp, 0);
                return temp.Cast<T>().GetEnumerator();
            }
        }

19 View Source File : ACBrIBGE.cs
License : MIT License
Project Creator : ACBrNet

private void ProcessarResposta(string resposta)
		{
			try
			{
				Resultados.Clear();

				var buffer = resposta.ToLower();
				var pos = buffer.IndexOf("<div id=\"miolo_interno\">", StringComparison.Ordinal);
				if (pos <= 0) return;

				buffer = buffer.Substring(pos, buffer.Length - pos);
				buffer = buffer.GetStrBetween("<table ", "</table>");

				var rows = Regex.Matches(buffer, @"(?<1><TR[^>]*>\s*<td.*?</tr>)", RegexOptions.Singleline | RegexOptions.IgnoreCase)
								.Cast<Match>()
								.Select(t => t.Value)
								.ToArray();

				if (rows.Length < 2) return;

				for (var i = 1; i < rows.Length; i++)
				{
					var columns = Regex.Matches(rows[i], @"<td[^>](.+?)<\/td>", RegexOptions.Singleline | RegexOptions.IgnoreCase)
									   .Cast<Match>()
									   .Select(t => t.Value.StripHtml().Replace(" ", string.Empty).Trim())
									   .ToArray();

					var municipio = new ACBrMunicipio
					{
						CodigoUF = columns[0].ToInt32(),
						UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), columns[1].ToUpper()),
						Codigo = columns[2].ToInt32(),
						Nome = columns[3].ToreplacedleCase(),
						Area = columns[4].ToDecimal()
					};

					Resultados.Add(municipio);
				}
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao processar retorno.");
			}
		}

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<string> LastChanceToFindAdjective(Feeling? feeling, SortedSet<object> alreadyProvidedValues, IFuzz fuzzer)
        {
            var allPossibleValues = Adjectives.PerFeeling[feeling.Value];

            var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<string>()).ToArray();

            if (remainingCandidates.Any())
            {
                var adjective = fuzzer.PickOneFrom(remainingCandidates);
                return new Maybe<string>(adjective);
            }

            return new Maybe<string>();
        }

19 View Source File : ActionManifestManager.cs
License : MIT License
Project Creator : actions

private ActionExecutionData ConvertRuns(
            IExecutionContext executionContext,
            TemplateContext templateContext,
            TemplateToken inputsToken,
            String fileRelativePath,
            MappingToken outputs = null)
        {
            var runsMapping = inputsToken.replacedertMapping("runs");
            var usingToken = default(StringToken);
            var imageToken = default(StringToken);
            var argsToken = default(SequenceToken);
            var entrypointToken = default(StringToken);
            var envToken = default(MappingToken);
            var mainToken = default(StringToken);
            var pluginToken = default(StringToken);
            var preToken = default(StringToken);
            var preEntrypointToken = default(StringToken);
            var preIfToken = default(StringToken);
            var postToken = default(StringToken);
            var postEntrypointToken = default(StringToken);
            var postIfToken = default(StringToken);
            var steps = default(List<Pipelines.Step>);

            foreach (var run in runsMapping)
            {
                var runsKey = run.Key.replacedertString("runs key").Value;
                switch (runsKey)
                {
                    case "using":
                        usingToken = run.Value.replacedertString("using");
                        break;
                    case "image":
                        imageToken = run.Value.replacedertString("image");
                        break;
                    case "args":
                        argsToken = run.Value.replacedertSequence("args");
                        break;
                    case "entrypoint":
                        entrypointToken = run.Value.replacedertString("entrypoint");
                        break;
                    case "env":
                        envToken = run.Value.replacedertMapping("env");
                        break;
                    case "main":
                        mainToken = run.Value.replacedertString("main");
                        break;
                    case "plugin":
                        pluginToken = run.Value.replacedertString("plugin");
                        break;
                    case "post":
                        postToken = run.Value.replacedertString("post");
                        break;
                    case "post-entrypoint":
                        postEntrypointToken = run.Value.replacedertString("post-entrypoint");
                        break;
                    case "post-if":
                        postIfToken = run.Value.replacedertString("post-if");
                        break;
                    case "pre":
                        preToken = run.Value.replacedertString("pre");
                        break;
                    case "pre-entrypoint":
                        preEntrypointToken = run.Value.replacedertString("pre-entrypoint");
                        break;
                    case "pre-if":
                        preIfToken = run.Value.replacedertString("pre-if");
                        break;
                    case "steps":
                        var stepsToken = run.Value.replacedertSequence("steps");
                        steps = PipelineTemplateConverter.ConvertToSteps(templateContext, stepsToken);
                        templateContext.Errors.Check();
                        break;
                    default:
                        Trace.Info($"Ignore run property {runsKey}.");
                        break;
                }
            }

            if (usingToken != null)
            {
                if (string.Equals(usingToken.Value, "docker", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(imageToken?.Value))
                    {
                        throw new ArgumentNullException($"You are using a Container Action but an image is not provided in {fileRelativePath}.");
                    }
                    else
                    {
                        return new ContainerActionExecutionData()
                        {
                            Image = imageToken.Value,
                            Arguments = argsToken,
                            EntryPoint = entrypointToken?.Value,
                            Environment = envToken,
                            Pre = preEntrypointToken?.Value,
                            InitCondition = preIfToken?.Value ?? "always()",
                            Post = postEntrypointToken?.Value,
                            CleanupCondition = postIfToken?.Value ?? "always()"
                        };
                    }
                }
                else if (string.Equals(usingToken.Value, "node12", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(mainToken?.Value))
                    {
                        throw new ArgumentNullException($"You are using a JavaScript Action but there is not an entry JavaScript file provided in {fileRelativePath}.");
                    }
                    else
                    {
                        return new NodeJSActionExecutionData()
                        {
                            Script = mainToken.Value,
                            Pre = preToken?.Value,
                            InitCondition = preIfToken?.Value ?? "always()",
                            Post = postToken?.Value,
                            CleanupCondition = postIfToken?.Value ?? "always()"
                        };
                    }
                }
                else if (string.Equals(usingToken.Value, "composite", StringComparison.OrdinalIgnoreCase))
                {
                    if (steps == null)
                    {
                        throw new ArgumentNullException($"You are using a composite action but there are no steps provided in {fileRelativePath}.");
                    }
                    else
                    {
                        return new CompositeActionExecutionData()
                        {
                            Steps = steps.Cast<Pipelines.ActionStep>().ToList(),
                            PreSteps = new List<Pipelines.ActionStep>(),
                            PostSteps = new Stack<Pipelines.ActionStep>(),
                            InitCondition = "always()",
                            CleanupCondition = "always()",
                            Outputs = outputs
                        };
                    }
                }
                else
                {
                    throw new ArgumentOutOfRangeException($"'using: {usingToken.Value}' is not supported, use 'docker' or 'node12' instead.");
                }
            }
            else if (pluginToken != null)
            {
                return new PluginActionExecutionData()
                {
                    Plugin = pluginToken.Value
                };
            }

            throw new NotSupportedException(nameof(ConvertRuns));
        }

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
            string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))

            {
                //X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);

                log.Info($"Got SMSID from registration of: {clientId}");

                // create base DDR Message
                ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
                {
                    // Add necessary discovery data
                    SmsId = clientId,
                    ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
                    SiteCode = SiteCode,
                    DomainName = domainName,
                    NetBiosName = clientName
                };

                ddrMessage.Discover();
                // Add our certificate for message signing
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
                ddrMessage.Settings.HostName = CMServerName;
                ddrMessage.Settings.Compression = MessageCompression.Zlib;
                ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
                if (enumerateAndAddCustomDdr)
                {
                    //see current value for the DDR message
                    var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");

                    ////retrieve actual setting
                    string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                                        select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();

                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();

                    ////retrieve reported value
                    xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());

                    ////Set OS to correct setting
                    xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";

                    ////Remove the instance
                    ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));

                    CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
                    {
                        PlatformId = osCaption
                    };
                    InventoryInstance instance = new InventoryInstance(FixedOSRecord);

                    ////Add new instance
                    ddrMessage.DdrInstances.Add(instance);
                }

                ddrMessage.SendMessage(Sender);

                ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
                hinvMessage.Settings.HostName = CMServerName;
                hinvMessage.SmsId = clientId;
                hinvMessage.Settings.Compression = MessageCompression.Zlib;
                hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                //hinvMessage.Settings.Security.EncryptMessage = true;
                hinvMessage.Discover();

                var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
                foreach (string Clreplaced in Clreplacedes)
                {
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
                foreach (string Clreplaced in SMSClreplacedes)
                {
                    log.Info($"---Adding clreplaced : [{Clreplaced}]");
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                hinvMessage.Validate(Sender);
                hinvMessage.SendMessage(Sender);
            };
        }

19 View Source File : EnumerableExtraExtensions.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static T? FirstOrNullable<T>(this IEnumerable<T> source, Func<T, bool> predicate)
		where T : struct
		{
			source.ThrowOnNull(nameof(source));
			return source.Cast<T?>().FirstOrDefault(v => predicate(v.Value));
		}

19 View Source File : MangaDB.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override List<replacedle> Get()
        {
            return mangas.Cast<replacedle>().ToList();
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : adamped

public void Sync()
		{
			// All rows that have changed since last sync
			var changed = _rows.Where(x => x.LastUpdated >= _lastSync || (x.Deleted != null && x.Deleted >= _lastSync)).ToList();
			_server.PushSync(changed.Cast<TableSchema>().ToList());

			foreach (var row in _server.PullSync(_lastSync))
				if (!_rows.Any(x => x.Id == row.Id)) // Does not exist, hence insert
					InsertRow(new ClientTableSchema(row));
				else if (row.Deleted.HasValue)
					DeleteRow(row.Id);
				else
					UpdateRow(new ClientTableSchema(row));

			_lastSync = DateTimeOffset.Now;
		}

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 17MKH

public static OptionCollectionResultModel ToResult<T>(bool ignoreUnKnown = false)
    {
        var enumType = typeof(T);

        if (!enumType.IsEnum)
            return null;

        if (ignoreUnKnown)
        {
            #region ==忽略UnKnown属性==

            if (!ListCacheNoIgnore.TryGetValue(enumType.TypeHandle, out OptionCollectionResultModel list))
            {
                var options = Enum.GetValues(enumType).Cast<Enum>()
                    .Where(m => !m.ToString().Equals("UnKnown"));

                list = Options2Collection(options);

                ListCacheNoIgnore.TryAdd(enumType.TypeHandle, list);
            }

            return list;

            #endregion ==忽略UnKnown属性==
        }
        else
        {
            #region ==包含UnKnown选项==

            if (!ListCache.TryGetValue(enumType.TypeHandle, out OptionCollectionResultModel list))
            {
                var options = Enum.GetValues(enumType).Cast<Enum>();
                list = Options2Collection(options);
                ListCache.TryAdd(enumType.TypeHandle, list);
            }

            return list;

            #endregion ==包含UnKnown选项==
        }
    }

19 View Source File : RxShellItem.cs
License : MIT License
Project Creator : adospace

protected override IEnumerable<VisualNode> RenderChildren()
        {
            return _items.Cast<VisualNode>();
        }

19 View Source File : AuditTrailRepository.cs
License : Apache License 2.0
Project Creator : aadreja

public List<IAuditTrail> ReadAllAuditTrail(object id)
        {
            var lstAudit = ReadAll("*", $"[email protected] AND [email protected]", 
                new { TableName = enreplacedyTableInfo.Name, RecordId = id.ToString() }, 
                Config.CreatedOnColumnName + " ASC");

            var result = lstAudit.ToList();

            result.ForEach(p => p.Split());

            return result.Cast<IAuditTrail>().ToList();

        }

19 View Source File : EnumCache.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static EnumStrings Create(Type enumType)
            {
                var enumItems = Enum.GetValues(enumType)
                                    .Cast<Enum>()
                                    .Select(i => new EnumItem(i))
                                    .ToList();

                return ArrayEnumStrings.CanHandle(enumItems)
                    ? (EnumStrings)new ArrayEnumStrings(enumItems)
                    : new DictionaryEnumStrings(enumItems);
            }

19 View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH

private void LoadEnums(ModuleDescriptor descriptor)
    {
        var layer = descriptor.Layerreplacedemblies;

        if (layer.Core == null)
            return;

        var enumTypes = layer.Core.GetTypes().Where(m => m.IsEnum);
        foreach (var enumType in enumTypes)
        {
            var enumDescriptor = new ModuleEnumDescriptor
            {
                Name = enumType.Name,
                Type = enumType,
                Options = Enum.GetValues(enumType).Cast<Enum>().Where(m => !m.ToString().EqualsIgnoreCase("UnKnown")).Select(x => new OptionResultModel
                {
                    Label = x.ToDescription(),
                    Value = x
                }).ToList()
            };

            descriptor.EnumDescriptors.Add(enumDescriptor);
        }
    }

19 View Source File : DataGridExtension.cs
License : MIT License
Project Creator : ABTSoftware

private static void OnDataGridColumnsPropertyChanged(DependencyObject d,
               DependencyPropertyChangedEventArgs e)
        {
            if (d.GetType() == typeof(DataGrid))
            {
                DataGrid myGrid = d as DataGrid;

                var Columns = (ObservableCollection<DataGridColumn>)e.NewValue;

                if (Columns != null)
                {
                    myGrid.Columns.Clear();

                    if (Columns != null && Columns.Count > 0)
                    {
                        foreach (DataGridColumn dataGridColumn in Columns)
                        {
                            myGrid.Columns.Add(dataGridColumn);
                        }
                    }


                    Columns.CollectionChanged += delegate(object sender, NotifyCollectionChangedEventArgs args)
                    {
                        if (args.NewItems != null)
                        {
                            foreach (DataGridColumn column in args.NewItems.Cast<DataGridColumn>())
                            {
                                myGrid.Columns.Add(column);
                            }
                        }

                        if (args.OldItems != null)
                        {

                            foreach (DataGridColumn column in args.OldItems.Cast<DataGridColumn>())
                            {
                                myGrid.Columns.Remove(column);
                            }
                        }
                    };

                }
            }
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<string> LastChanceToFindLastName(string firstName, SortedSet<object> alreadyProvidedValues, IFuzz fuzzer)
        {
            var continent = Locations.FindContinent(firstName);
            var allPossibleValues = LastNames.PerContinent[continent];

            var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<string>()).ToArray();

            if (remainingCandidates.Any())
            {
                var lastName = fuzzer.PickOneFrom(remainingCandidates);
                return new Maybe<string>(lastName);
            }

            return new Maybe<string>();
        }

19 View Source File : Files.vm.cs
License : MIT License
Project Creator : Accelerider

private async void DeleteCommandExecute(IList files)
        {
            var currentFolder = CurrentFolder;
            var fileArray = files.Cast<ILazyTreeNode<INetDiskFile>>().ToArray();

            var errorFileCount = 0;
            foreach (var file in fileArray)
            {
                if (!await CurrentNetDiskUser.DeleteFileAsync(file.Content)) errorFileCount++;
            }

            if (errorFileCount < fileArray.Length)
            {
                await RefreshFilesCommand.Execute();
            }

            GlobalMessageQueue.Enqueue($"({fileArray.Length - errorFileCount}/{fileArray.Length}) files have been deleted.");
        }

19 View Source File : EnumHelper.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static List<Enum> GetFlags(this Enum e)
        {
            return Enum.GetValues(e.GetType()).Cast<Enum>().Where(e.HasFlag).ToList();
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<T> LastChanceToFindNotAlreadyPickedValue<T>(SortedSet<object> alreadyProvidedValues, IList<T> candidates, IFuzz fuzzer)
        {
            var allPossibleValues = candidates.ToArray();

            var remainingCandidates = allPossibleValues.Except<T>(alreadyProvidedValues.Cast<T>()).ToArray();

            if (remainingCandidates.Any())
            {
                var index = fuzzer.GenerateInteger(0, remainingCandidates.Length - 1);
                var pickOneFrom = remainingCandidates[index];

                return new Maybe<T>(pickOneFrom);
            }

            return new Maybe<T>();
        }

19 View Source File : BodyPart.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static List<BodyPart> GetFlags(BodyPart bodyParts)
        {
            return Enum.GetValues(typeof(BodyPart)).Cast<BodyPart>().Where(p => bodyParts.HasFlag(p)).ToList();
        }

19 View Source File : SegmentedControl.cs
License : MIT License
Project Creator : 1iveowl

private void OnItemsSourceChanged()
        {
            var itemsSource = ItemsSource;
            var items = itemsSource as IList;
            if (items == null && itemsSource is IEnumerable list)
                items = list.Cast<object>().ToList();

            if (items != null)
            {
                var textValues = items as IEnumerable<string>;
                if (textValues == null && items.Count > 0 && items[0] is string)
                    textValues = items.Cast<string>();

                if (textValues != null)
                {
                    Children = new List<SegmentedControlOption>(textValues.Select(child => new SegmentedControlOption {Text = child}));
                    OnSelectedItemChanged(true);
                }
                else
                {
                    var textPropertyName = TextPropertyName;
                    if (textPropertyName != null)
                    {
                        var newChildren = new List<SegmentedControlOption>();
                        foreach (var item in items)
                            newChildren.Add(new SegmentedControlOption { Item = item, TextPropertyName = textPropertyName });
                        Children = newChildren;
                        OnSelectedItemChanged(true);
                    }
                }
            }
        }

19 View Source File : WorldObject.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public Dictionary<PropertyInt, int?> GetProperties(WorldObject wo)
        {
            var props = new Dictionary<PropertyInt, int?>();

            var fields = Enum.GetValues(typeof(PropertyInt)).Cast<PropertyInt>();
            foreach (var field in fields)
            {
                var prop = wo.GetProperty(field);
                props.Add(field, prop);
            }
            return props;
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<char> LastChanceToFindLetter(SortedSet<object> alreadyProvidedValues, IFuzz fuzzer)
        {
            var allPossibleValues = LoremFuzzer.Alphabet;

            var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<char>()).ToArray();
            
            if (remainingCandidates.Any())
            {
                var letter = fuzzer.PickOneFrom<char>(remainingCandidates);
                return new Maybe<char>(letter);
            }

            return new Maybe<char>();
        }

19 View Source File : VssJsonMediaTypeFormatter.cs
License : MIT License
Project Creator : actions

public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            // Do not wrap byte arrays as this is incorrect behavior (they are written as base64 encoded strings and
            // not as array objects like other types).

            Type typeToWrite = type;
            if (!m_bypreplacedSafeArrayWrapping
                && typeof(IEnumerable).GetTypeInfo().IsreplacedignableFrom(type.GetTypeInfo())
                && !type.Equals(typeof(Byte[]))
                && !type.Equals(typeof(JObject)))
            {
                typeToWrite = typeof(VssJsonCollectionWrapper);

                // IEnumerable will need to be materialized if they are currently not.
                object materializedValue = value is ICollection || value is string ?
                    value : // Use the regular input if it is already materialized or it is a string
                    ((IEnumerable)value)?.Cast<Object>().ToList() ?? value; // Otherwise, try materialize it

                value = new VssJsonCollectionWrapper((IEnumerable)materializedValue);
            }
            return base.WriteToStreamAsync(typeToWrite, value, writeStream, content, transportContext);
        }

19 View Source File : EnumExtensions.cs
License : MIT License
Project Creator : 17MKH

public static OptionCollectionResultModel ToResult(this Enum value, bool ignoreUnKnown = false)
    {
        var enumType = value.GetType();

        if (!enumType.IsEnum)
            return null;

        var options = Enum.GetValues(enumType).Cast<Enum>()
            .Where(m => !ignoreUnKnown || !m.ToString().Equals("UnKnown"));

        return Options2Collection(options);
    }

19 View Source File : EnumerableExtraExtensions.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static T? FirstOrNullable<T>(this IEnumerable<T> source)
		where T : struct
		{
			source.ThrowOnNull(nameof(source));
			return source.Cast<T?>().FirstOrDefault();
		}

19 View Source File : ExpressionTree.Linq.cs
License : MIT License
Project Creator : 71

public static IEnumerable<Expression> Children(this Expression expression, bool allChildren = false)
        {
            if (allChildren)
                return new ExpressionEnumerator(expression);

            switch (expression)
            {
                case BinaryExpression binary:
                    return new[] { binary.Left, binary.Right };
                case BlockExpression block:
                    return block.Expressions.ToArray();
                case ConditionalExpression conditional:
                    return new[] { conditional.Test, conditional.IfTrue, conditional.IfFalse };
                case GotoExpression @goto:
                    return new[] { @goto.Value };
                case IndexExpression index:
                    return MakeArray(index.Object, index.Arguments);
                case InvocationExpression invocation:
                    return MakeArray(invocation.Expression, invocation.Arguments);
                case LabelExpression label:
                    return new[] { label.DefaultValue };
                case LambdaExpression lambda:
                    return lambda.Body.Children();
                case ListInitExpression listInit:
                    return MakeArray(listInit.NewExpression, listInit.Initializers.SelectMany(x => x.Arguments));
                case LoopExpression loop:
                    return new[] { loop.Body };
                case MemberExpression member:
                    return new[] { member.Expression };
                case MemberInitExpression memberInit:
                    return new[] { memberInit.NewExpression };
                case MethodCallExpression call:
                    return MakeArray(call.Object, call.Arguments);
                case NewArrayExpression newArray:
                    return newArray.Expressions.ToArray();
                case NewExpression @new:
                    return @new.Arguments.ToArray();
                case RuntimeVariablesExpression runtimeVar:
                    return runtimeVar.Variables.Cast<Expression>().ToArray();
                case SwitchExpression @switch:
                    return MakeArray(@switch.SwitchValue, @switch.DefaultBody, @switch.Cases.SelectMany(x => x.TestValues.Prepend(x.Body)));
                case TryExpression @try:
                    return MakeArray(@try.Body, @try.Fault, @try.Handlers.Select(x => x.Body), @try.Finally);
                case TypeBinaryExpression typeBinary:
                    return new[] { typeBinary.Expression };
                case UnaryExpression unary:
                    return new[] { unary.Operand };

                default:
                    return new Expression[0];
            }
        }

19 View Source File : EnumerableExtraExtensions.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static T? LastOrNullable<T>(this IEnumerable<T> source)
		where T : struct
		{
			source.ThrowOnNull(nameof(source));
			return source.Cast<T?>().LastOrDefault();
		}

19 View Source File : UserControlBase.cs
License : MIT License
Project Creator : 2881099

protected List<TextBoxX> InitLostFocus(Control control, Highlighter highlighter)
        {
            textBoxs = control.Controls.Cast<Control>().Where(a => (a is TextBoxX textBox))
            .OrderBy(a => a.Name).Select(a => a as TextBoxX).ToList();
            textBoxs.ForEach(a =>
            {
                a.LostFocus += (s, e) =>
                {
                    if (!string.IsNullOrEmpty(((TextBoxX)s).Text))
                    {
                        highlighter.SetHighlightColor(a, eHighlightColor.Green);
                    }
                };

            });
            return textBoxs;
        }

19 View Source File : TextSpan.cs
License : MIT License
Project Creator : adamant

[System.Diagnostics.Contracts.Pure]
        public static TextSpan Covering(params TextSpan?[] spans)
        {
            return spans.Where(s => s != null).Cast<TextSpan>().Aggregate(Covering);
        }

19 View Source File : HentaiDB.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override List<replacedle> Get()
        {
            return hentais.Cast<replacedle>().ToList();
        }

19 View Source File : Matrix.cs
License : MIT License
Project Creator : adamped

public static SKMatrix ToSkMatrix(List<float> matrix4)
        {
            return ToSkMatrix(matrix4.Cast<double>().ToList());
        }

19 View Source File : DataContext.cs
License : MIT License
Project Creator : 0x0ade

public T[] GetRefs<T>() where T : DataType<T>
            => GetRefs(DataTypeToID[typeof(T)]).Cast<T>().ToArray();

19 View Source File : RxLayout.cs
License : MIT License
Project Creator : adospace

public void Add(object genericNode)
        {
            if (genericNode == null)
            {
                return;
            }

            if (genericNode is VisualNode visualNode)
            {
                _internalChildren.Add(visualNode);
            }
            else if (genericNode is IEnumerable nodes)
            {
                foreach (var node in nodes.Cast<VisualNode>())
                    _internalChildren.Add(node);
            }
            else
            {
                throw new NotSupportedException($"Unable to add value of type '{genericNode.GetType()}' under {typeof(T)}");
            }        
        }

19 View Source File : AuditTrailKeyValueRepository.cs
License : Apache License 2.0
Project Creator : aadreja

public List<IAuditTrail> ReadAllAuditTrail(object id)
        {
            var lstAudit = ReadAll("*", $"[email protected] AND [email protected]", new { TableName = enreplacedyTableInfo.Name, RecordId = id.ToString() }, Config.CreatedOnColumnName + " ASC").ToList();

            foreach (AuditTrailKeyValue audit in lstAudit)
            {
                var lstAuditTrailDetail = detailRepo.ReadAll(null, "[email protected]", new { audittrailid = audit.AuditTrailId }).ToList();
                audit.lstAuditTrailDetail = lstAuditTrailDetail.Cast<IAuditTrailDetail>().ToList();
            }

            return lstAudit.Cast<IAuditTrail>().ToList();
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<int> LastChanceToFindNotAlreadyProvidedInteger(SortedSet<object> alreadyProvidedValues, int? minValue, int? maxValue, IFuzz fuzzer)
        {
            minValue = minValue ?? int.MinValue;
            maxValue = maxValue ?? int.MaxValue;

            var allPossibleValues = Enumerable.Range(minValue.Value, maxValue.Value).ToArray();

            var remainingCandidates = allPossibleValues.Except<int>(alreadyProvidedValues.Cast<int>()).ToArray();

            if (remainingCandidates.Any())
            {
                var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
                return new Maybe<int>(pickOneFrom);
            }

            return new Maybe<int>();
        }

19 View Source File : Ribbon.cs
License : GNU General Public License v3.0
Project Creator : 0dteam

public static ILookup<string, string> HeaderLookup(this MailItem mailItem)
        {
            var headerString = mailItem.HeaderString();
            var headerMatches = Regex.Matches
                (headerString, HeaderRegex, RegexOptions.Multiline).Cast<Match>();
            return headerMatches.ToLookup(
                h => h.Groups["header_key"].Value,
                h => h.Groups["header_value"].Value);
        }

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = [email protected]"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

19 View Source File : VerifyHelper.cs
License : MIT License
Project Creator : 1996v

public static T Is<T>(this T actual, T expected)
        {
            if (expected == null)
            {
                replacedert.Null(actual);
                return actual;
            }

            if (typeof(T) != typeof(string) && typeof(IEnumerable).GetTypeInfo().IsreplacedignableFrom(typeof(T)))
            {
                replacedert.Equal(
                    ((IEnumerable)expected).Cast<object>().ToArray(),
                    ((IEnumerable)actual).Cast<object>().ToArray());
                return actual;
            }

            replacedert.Equal(expected, actual);
            return actual;
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static Maybe<int> LastChanceToFindAge(SortedSet<object> alreadyProvidedValues, int minAge, int maxAge, IFuzz fuzzer)
        {
            var allPossibleValues = Enumerable.Range(minAge, maxAge - minAge).ToArray();

            var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<int>()).ToArray();

            if (remainingCandidates.Any())
            {
                var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
                return new Maybe<int>(pickOneFrom);
            }

            return new Maybe<int>();
        }

19 View Source File : Files.vm.cs
License : MIT License
Project Creator : Accelerider

private async void DownloadCommandExecute(IList files)
        {
            var fileArray = files.Cast<ILazyTreeNode<INetDiskFile>>().ToArray();

            var (to, isDownload) = await DisplayDownloadDialogAsync(fileArray.Select(item => item.Content.Path.FileName));

            if (!isDownload) return;

            var currentFolderPathLength = CurrentFolder.Content.Path.FullPath.Length;
            var fileNames = new List<string>(fileArray.Length);
            foreach (var fileNode in fileArray)
            {
                var targetPath = to;
                var substringStart = currentFolderPathLength;
                if (fileNode.Content.Type == FileType.FolderType)
                {
                    var rootPath = fileNode.Content.Path.FullPath.Substring(substringStart);
                    targetPath = CombinePath(to, rootPath).GetUniqueLocalPath(Directory.Exists);
                    substringStart += rootPath.Length;
                }

                await fileNode.ForEachAsync(file =>
                {
                    if (file.Type == FileType.FolderType) return;

                    var downloadingFile = CurrentNetDiskUser.Download(
                        file,
                        CombinePath(targetPath, file.Path.FolderPath.Substring(substringStart)));
                    downloadingFile.Operations.Ready();
                    // Send this transfer item to the downloading view model.
                    EventAggregator.GetEvent<TransferItemsAddedEvent>().Publish(downloadingFile);
                    fileNames.Add(downloadingFile.File.Path.FileName);
                }, CancellationToken.None);
            }

            if (fileNames.Any())
            {
                var fileName = fileNames.First().TrimMiddle(40);
                var message = fileNames.Count == 1
                    ? string.Format(UiStrings.Message_AddedFileToDownloadList, fileName)
                    : string.Format(UiStrings.Message_AddedFilesToDownloadList, fileName, fileNames.Count);
                GlobalMessageQueue.Enqueue(message);
            }
            else
            {
                GlobalMessageQueue.Enqueue("No Files Found");
            }
        }

See More Examples