本文整理汇总了C#中System.Collections.ArrayList.Cast方法的典型用法代码示例。如果您正苦于以下问题:C# ArrayList.Cast方法的具体用法?C# ArrayList.Cast怎么用?C# ArrayList.Cast使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.ArrayList
的用法示例。
在下文中一共展示了ArrayList.Cast方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
ArrayList pessoas = new ArrayList();
pessoas.Add("Agnaldo");
pessoas.Add("Alexandre");
pessoas.Add("Vítor");
pessoas.Add("Sincic");
pessoas.Add("Laerte");
pessoas.Add("Thiago");
pessoas.Add("Roberto");
//var lista = from p in pessoas
// select p;
//Could not find an implementation of the query pattern for source type 'System.Collections.ArrayList'. 'Select' not found. Consider explicitly specifying the type of the range variable 'p'.
var listaCast = from p in pessoas.Cast<String>()
select p;
ObjectDumper.Write(listaCast);
Console.WriteLine();
var listaDeclaracaoTipo = from String p in pessoas
select p;
ObjectDumper.Write(listaDeclaracaoTipo);
Console.ReadKey();
}
示例2: TestAdapter
public void TestAdapter()
{
var a = new ArrayList { 1, 5, 3, 3, 2, 4, 3 };
var sortedA = a.Cast<int>().OrderBy(i => i).ToList();
a.Sort(new ComparisonAdapter<int>(IntComparer));
CollectionAssert.AreEqual(sortedA, a);
}
示例3: LegacyListTest
public void LegacyListTest()
{
var names = new ArrayList()
{
"Peniel",
"Tafadzwa",
"Aime",
"Kuziva",
"Majd"
};
//Fluent API: first cast the arrayList to IEnumerable List<>
var nameWithJ = names.Cast<string>().Where(p => p.ToLower().Contains("j"));
Console.WriteLine("Names with J: ");
foreach (var j in nameWithJ)
{
Console.WriteLine($"\t{j}");
}
//Query syntax: first cast the ArrayList to IEnumerabli List<>
var nameWithI = from string i in names
where i.ToLower().Contains("i")
select i;
Console.WriteLine("\nNames with i: ");
foreach (var i in nameWithI)
{
Console.WriteLine($"\t{i}");
}
Assert.AreEqual(nameWithI.Count(), 3);
Assert.AreEqual(nameWithJ.Count(), 1);
}
示例4: DoJob
public override string DoJob()
{
StartRun();
var ppg = new PlayerProjectionGenerator( playerCache: null );
var gameList = new ArrayList();
// do any unplayed games
Logger.Debug( " Doing whole season" );
var s = new NflSeason( TimeKeeper.Season, loadGames: true, loadDivisions: false ); // long time to load
foreach ( var game in s.GameList )
if (! game.Played() )
gameList.Add( game );
var nGames = 0;
foreach ( var game in gameList.Cast<NFLGame>() )
{
ppg.Execute( game );
nGames++;
}
// records will be in the PGMETRIC table
StopRun();
var finishedMessage = string.Format( "Generated projections for {0} games", nGames );
Logger.Info( " {0}", finishedMessage );
return finishedMessage;
}
示例5: Main
static void Main(string[] args)
{
List<string> words = new List<string>(); // New string-typed list
words.Add("melon");
words.Add("avocado");
words.AddRange(new[] { "banana", "plum" });
words.Insert(0, "lemon"); // Insert at start
words.InsertRange(0, new[] { "peach", "nashi" }); // Insert at start
words.Remove("melon");
words.RemoveAt(3); // Remove the 4th element
words.RemoveRange(0, 2); // Remove first 2 elements
words.RemoveAll(s => s.StartsWith("n"));// Remove all strings starting in 'n'
Console.WriteLine(words[0]); // first word
Console.WriteLine(words[words.Count - 1]); // last word
foreach (string s in words) Console.WriteLine(s); // all words
List<string> subset = words.GetRange(1, 2); // 2nd->3rd words
string[] wordsArray = words.ToArray(); // Creates a new typed array
string[] existing = new string[1000];// Copy first two elements to the end of an existing array
words.CopyTo(0, existing, 998, 2);
List<string> upperCastWords = words.ConvertAll(s => s.ToUpper());
List<int> lengths = words.ConvertAll(s => s.Length);
ArrayList al = new ArrayList();
al.Add("hello");
string first = (string)al[0];
string[] strArr = (string[])al.ToArray(typeof(string));
List<string> list = al.Cast<string>().ToList();
}
示例6: PrintForm_Load
private void PrintForm_Load(object sender, EventArgs e)
{
var inif = new INIFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\eXpressPrint\\config.ini");
if (!string.IsNullOrEmpty(inif.Read("PRINT_OPT", "AUTO")))
{
if (inif.Read("PRINT_OPT", "AUTO").Equals("Y"))
PrintAndReturn(_PrintImage);
}
if (!string.IsNullOrEmpty(inif.Read("PRINT_SET", "COPIES")))
{
var arr = new ArrayList();
arr.AddRange(inif.Read("PRINT_SET", "COPIES").Split(','));
var sortedList = arr.Cast<string>().OrderBy(item => int.Parse(item));
foreach (var item in sortedList)
{
comboBoxNumOfCopies.Items.Add(item);
}
comboBoxNumOfCopies.Items.Insert(0,"--Select--");
comboBoxNumOfCopies.SelectedIndex = 0;
}
formState.Maximize(this);
txtNumberOfCopies.Focus();
}
示例7: Main
static void Main(string[] args)
{
var genericList = new List<int>();
var nonGenericList = new ArrayList();
for (var i = 0; i < 10000000; i++)
{
genericList.Add(1);
nonGenericList.Add(1);
}
var start = DateTime.Now;
double result = genericList.Sum();
var end = DateTime.Now;
var duration = end - start;
Console.WriteLine("Generic result: {0}\n generic time:{1}", result, duration.Milliseconds);
result = 0;
start = DateTime.Now;
result = nonGenericList.Cast<int>().Sum();
end = DateTime.Now;
duration = end - start;
Console.WriteLine("Generic result: {0}\n nongeneric time:{1}", result, duration.Milliseconds);
Console.ReadLine();
}
示例8: GetOutlet
public SyncResponseMasterDataInfo<OutletDTO> GetOutlet(QueryMasterData myQuery)
{
var response = new SyncResponseMasterDataInfo<OutletDTO>();
response.MasterData = new SyncMasterDataInfo<OutletDTO>();
response.MasterData.EntityName = MasterDataCollective.Outlet.ToString();
try
{
var costCentre = GetSyncCostCentre(myQuery.ApplicationId);
var query = _context.tblCostCentre.AsQueryable();
query = query.Where(n => n.CostCentreType == (int)CostCentreType.Outlet
&& (n.IM_Status == (int)EntityStatus.Active || n.IM_Status == (int)EntityStatus.Inactive || n.IM_Status == (int)EntityStatus.New));
var deletedQuery = _context.tblCostCentre.AsQueryable();
deletedQuery = deletedQuery.Where(n => n.CostCentreType == (int)CostCentreType.Outlet
&& (n.IM_Status == (int)EntityStatus.Deleted));
if (costCentre != null)
{
switch (costCentre.CostCentreType)
{
case CostCentreType.Distributor:
query = query.Where(n => n.ParentCostCentreId == costCentre.Id
&& n.IM_DateLastUpdated > myQuery.From);
deletedQuery = deletedQuery.Where(n => n.ParentCostCentreId == costCentre.Id
&& n.IM_DateLastUpdated > myQuery.From);
break;
case CostCentreType.DistributorSalesman:
var routeIds = GetRouteIds(costCentre, myQuery.From);
query = query.Where(n => routeIds.Contains(n.RouteId.Value));
deletedQuery = deletedQuery.Where(n => routeIds.Contains(n.RouteId.Value));
break;
}
}
query = query.OrderBy(s => s.IM_DateCreated);
deletedQuery = deletedQuery.OrderBy(s => s.IM_DateCreated);
if (myQuery.Skip.HasValue && myQuery.Take.HasValue)
query = query.Skip(myQuery.Skip.Value).Take(myQuery.Take.Value);
if (myQuery.Skip.HasValue && myQuery.Skip.Value == 0)
{
response.DeletedItems = deletedQuery.Select(s => s.Id).ToList();
}
var list = new ArrayList();
foreach (var item in query.ToArray())
{
list.Add(Map(item));
}
response.MasterData.MasterDataItems = list.Cast<OutletDTO>().ToArray();
// response.MasterData.MasterDataItems = query.ToList().Select(n => Map(n)).ToArray();
response.ErrorInfo = "Success";
}
catch (Exception ex)
{
response.ErrorInfo = ex.Message;
}
response.MasterData.LastSyncTimeStamp = DateTime.Now;
return response;
}
示例9: Select
public IEnumerable<Socket> Select(ICollection<Socket> handles)
{
Console.Write("Waiting for pending connections...");
var pending = new ArrayList(handles.ToArray());
Socket.Select(pending, null, null, 10000);
Console.WriteLine("done");
return pending.Cast<Socket>();
}
示例10: GetPricing
public SyncResponseMasterDataInfo<ProductPricingDTO> GetPricing(QueryMasterData q)
{
var response = new SyncResponseMasterDataInfo<ProductPricingDTO>();
response.MasterData = new SyncMasterDataInfo<ProductPricingDTO>();;
response.MasterData.EntityName = MasterDataCollective.Pricing.ToString();
try
{
var query = _context.tblPricing.AsQueryable();
query = query.Where(n =>
n.IM_Status == (int)EntityStatus.Active || n.IM_Status == (int)EntityStatus.Inactive);
var deletedQuery = _context.tblPricing.AsQueryable();
deletedQuery = deletedQuery.Where(n =>
n.IM_Status == (int)EntityStatus.Deleted);
var syncostcentre = GetSyncCostCentre(q.ApplicationId);
if (syncostcentre != null)
{
var pricingTiers = GetApplicablePricingTiers(syncostcentre);
query = query.Where(s => s.IM_DateLastUpdated > q.From && pricingTiers.Contains(s.Tier));
deletedQuery = deletedQuery.Where(s => s.IM_DateLastUpdated > q.From && pricingTiers.Contains(s.Tier));
}
query = query.OrderBy(s => s.IM_DateCreated);
deletedQuery = deletedQuery.OrderBy(s => s.IM_DateCreated);
if (q.Skip.HasValue && q.Take.HasValue)
query = query.Skip(q.Skip.Value).Take(q.Take.Value);
if (q.Skip.HasValue && q.Skip.Value == 0)
{
response.DeletedItems = deletedQuery.Select(s => s.id).ToList();
}
var list = new ArrayList();
foreach (var item in query.ToArray())
{
list.Add(Map(item));
}
response.MasterData.MasterDataItems = list.Cast<ProductPricingDTO>().ToArray();
response.ErrorInfo = "Success";
}
catch (Exception ex)
{
response.ErrorInfo = ex.Message;
}
response.MasterData.LastSyncTimeStamp = DateTime.Now;
return response;
}
示例11: Main
static void Main()
{
ArrayList list = new ArrayList { "First", "Second", "Third"};
var strings = list.Cast<string>();
foreach (string item in strings)
{
Console.WriteLine(item);
}
list = new ArrayList { 1, "not an int", 2, 3};
var ints = list.OfType<int>();
foreach (int item in ints)
{
Console.WriteLine(item);
}
}
示例12: JobAttachmentsImageMontage
public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext Database)
{
if (JobAttachments == null)
throw new ArgumentNullException("JobAttachments");
var attachments = JobAttachments.Cast<JobAttachment>().Where(a => a.MimeType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)).ToList();
if (attachments.Count > 0)
{
var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(Database)).ToList();
return new FileMontageImageExpressionResult(attachmentFilepaths);
}
else
return null;
}
示例13: AddimaginaryConsumer
private void AddimaginaryConsumer()
{
_consumers.Add(new Consumer(_stock - _requirement));
foreach (Supplier supplier in _suppliers)
{
ArrayList ratesList = new ArrayList();
foreach (int rate in supplier.GetRates())
{
ratesList.Add(rate);
}
ratesList.Add(0);
supplier.SetRates(ratesList.Cast<int>().ToArray());
}
}
示例14: GenericsPerformanceGains
public void GenericsPerformanceGains() //Generics perform so much better than normal collections
{
const int iterations = 10000000;
var stopwatch = new Stopwatch();
stopwatch.Start();
var list = new ArrayList();
for (var currentIteration = 0; currentIteration <= iterations; currentIteration++)
{
list.Add(currentIteration);
}
foreach (var value in list.Cast<int>()) //We need to perform a cast in every member of the list
{
}
stopwatch.Stop();
var arrayListMilliseconds = stopwatch.ElapsedMilliseconds;
stopwatch.Reset();
stopwatch.Start();
var intList = new List<int>();
for (var currentIteration = 0; currentIteration <= iterations; currentIteration++)
{
intList.Add(currentIteration); //No cast is required
}
foreach (var integer in intList)
{
var value = integer;
}
stopwatch.Stop();
var listMilliseconds = stopwatch.ElapsedMilliseconds;
//List<T> will always outperform ArrayList, CLR performs internal optimizations as well
Assert.IsTrue(arrayListMilliseconds > listMilliseconds);
}
示例15: MultipleIterationsYieldSameResults
public void MultipleIterationsYieldSameResults()
{
var accumulator = new ArrayList();
using (var process = MockRepository.GenerateStub<EtlProcess>())
{
process.Stub(x => x.TranslateRows(null)).IgnoreArguments()
.WhenCalled(x => x.ReturnValue = x.Arguments[0]);
process.PipelineExecuter = new SingleThreadedPipelineExecuter();
process.Register(new GenericEnumerableOperation(new[] {Row.FromObject(new {Prop = "Hello"})}));
process.Register(new OutputSpyOperation(2, r => accumulator.Add(r["Prop"])));
process.Execute();
}
Assert.Equal(accumulator.Cast<string>().ToArray(), Enumerable.Repeat("Hello", 2).ToArray());
}