本文整理汇总了C#中List.AsParallel方法的典型用法代码示例。如果您正苦于以下问题:C# List.AsParallel方法的具体用法?C# List.AsParallel怎么用?C# List.AsParallel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类List
的用法示例。
在下文中一共展示了List.AsParallel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Index
public ActionResult Index(FormCollection formCollection)
{
var dossierId = Convert.ToInt32(formCollection["dossierId"]);
var fields = fService.GetFieldsByDossier(dossierId);
var list = new List<FieldInputz>();
foreach (var field in fields)
{
var f = new FieldInputz();
f.InjectFrom(field);
decimal v;
if (!decimal.TryParse(formCollection["c" + f.Id], out v))
f.ErrorMessage = "valoarea " + formCollection["c" + f.Id] + " nu este valida pentru acest camp";
f.Value = v;
list.Add(f);
}
if (list.Any(o => o.HasError))
{
ViewData["dossierId"] = dossierId;
return View(list);
}
var fieldValues = list.AsParallel().Select(
fieldInputz => new FieldValue { FieldId = fieldInputz.Id, Value = fieldInputz.Value, DossierId = dossierId }).ToList();
dService.Init(fieldValues, dossierId);
return View("success");
}
示例2: GetUrlsFromPage
protected List<string> GetUrlsFromPage(string pageUrl)
{
var urls = new List<string>();
try
{
var html = Client.RetrieveHtmlStrGet(pageUrl).Result;
urls = RegexHelper.GetMatchStr(html, @"(\/detail-)[0-9]{0,20}").Distinct().Select(x => URL_DTLS + x).ToList();
var res = urls.AsParallel().WithDegreeOfParallelism(ParallismDegree).Select(x =>
new RealEstateE()
{
Url = x.Trim(),
State = 0,
RecordStatus = 1,
Source = SourceName
}
).ToList();
DataHelper.InsertRealEstateE(res);
}
catch (Exception ex)
{
lock (sync)
{
File.AppendAllText("D:/RE/A_" + this.GetType().Name + ".log", DateTime.Now.ToString("yyyyMMdd HH:mm") + "," + pageUrl + "," + ex.GetBaseException().Message + "\r\n");
}
}
return urls;
}
示例3: GetSimilar
/// <summary>
/// To do. Create a clever search algorithm.
/// </summary>
/// <param name="Word"></param>
/// <param name="Collection"></param>
/// <returns></returns>
public string GetSimilar(string Word, List<string> Collection)
{
if (Word.IsNullOrEmpty())
{
return Word;
}
Dictionary<string, int> keys = new Dictionary<string, int>();
/*foreach (string s in words.Keys)
{
if (s.EndsWith(Word))
{
keys.Add(s, s.Length);
}
}*/
Collection.AsParallel().ForAll(s =>
{
if (s.EndsWith(Word))
{
keys.Add(s, s.Length);
}
});
if (!keys.Any() && Word.Length > 2)
{
return this.GetSimilar(Word.Substring(1), Collection);
}
string key = keys.OrderBy(val => val.Value).FirstOrDefault().Key;
return key;
}
示例4: H
public static void H()
{
Console.WriteLine("loading..");
//init some stuff
List<string> list = new List<string>();
// Stopwatch sw = new Stopwatch();
Random r = new Random();
double sum = 0;
DateTime dt;
for (int i = 0; i < 1000000; i++)
{
list.Add(r.Next(0, 999999).ToString());
}
//non parallel time
Console.WriteLine("starting");
dt = DateTime.Now;
foreach (string f in list)
{
MD5(f);
}
Console.WriteLine($"non parallel time: {(DateTime.Now - dt).Seconds} seconds");
//parallel
sum = 0;
dt = DateTime.Now;
list.AsParallel().ForAll(str => MD5(str));
Console.WriteLine($"parallel time:{ (DateTime.Now - dt).Seconds} seconds");
Console.WriteLine("end");
}
示例5: IndexPrograms
public static void IndexPrograms()
{
// todo why there is a lock??
lock (lockObject)
{
var sources = DefaultProgramSources();
if (_settings.ProgramSources != null &&
_settings.ProgramSources.Count(o => o.Enabled) > 0)
{
sources.AddRange(_settings.ProgramSources);
}
_sources = sources.AsParallel()
.Where(s => s.Enabled && SourceTypes.ContainsKey(s.Type))
.Select(s =>
{
var sourceClass = SourceTypes[s.Type];
var constructorInfo = sourceClass.GetConstructor(new[] { typeof(ProgramSource) });
var programSource = constructorInfo?.Invoke(new object[] { s }) as IProgramSource;
return programSource;
})
.Where(s => s != null).ToList();
_programs = _sources.AsParallel()
.SelectMany(s => s.LoadPrograms())
// filter duplicate program
.GroupBy(x => new { ExecutePath = x.Path, ExecuteName = x.ExecutableName })
.Select(g => g.First())
.ToList();
_cache.Programs = _programs;
}
}
示例6: MoveFood
private void MoveFood(object sender, ElapsedEventArgs e)
{
this.Position = this.Position + this._direction * (40 - this._salts);
List<Virus> clients = new List<Client>(this.Realm.Clients).OfType<Virus>().ToList();
// Verifica se algum virus vai comer
Virus virus = clients.AsParallel().FirstOrDefault(v => v.InsideClient(this.Position));
if (virus != null)
{
virus.Score += this.Score;
this.StopMove();
this.Realm.RemoveFood(this);
if (virus.Score > 200)
virus.Split(this._direction);
if (this._time != null)
this._time.Stop();
}
else
{
if (this._salts++ > 10)
this._time.Stop();
}
}
示例7: Main
static void Main(string[] args)
{
List<Student> list = new List<Student>()
{
new Student(){ ID=1, Name="jack", Age=20},
new Student(){ ID=1, Name="mary", Age=25},
new Student(){ ID=1, Name="joe", Age=29},
new Student(){ ID=1, Name="Aaron", Age=25},
};
//这里我们会对age建立一组键值对
var map = list.AsParallel().ToLookup(i => i.Age, count => 1);
//化简统计
var reduce = from IGrouping<int, int> singleMap
in map.AsParallel()
select new
{
Age = singleMap.Key,
Count = singleMap.Count()
};
///最后遍历
reduce.ForAll(i =>
{
Console.WriteLine("当前Age={0}的人数有:{1}人", i.Age, i.Count);
});
Console.Read();
}
示例8: Search
/// <summary>
/// Выполняет поиск
/// </summary>
/// <param name="article"></param>
/// <returns></returns>
public IList<SearchResultItem> Search(string article)
{
// Список всех поставщиков
var vendors = new List<IVendorSearcher>();
// Формируем список поставщиков исходя из настроек
var settingsRep = Locator.GetService<ISettingsRepository>();
if (settingsRep.GetValue<bool>("search_autotrader"))
{
vendors.Add(new AutoTradeSearcher());
}
if (settingsRep.GetValue<bool>("search_mxgroup"))
{
vendors.Add(new MXGroupSearcher());
}
if (settingsRep.GetValue<bool>("search_berg"))
{
vendors.Add(new BergSearcher());
}
// Выбираем данные параллельно
var fetched = vendors.AsParallel().Select(v => v.Search(article));
// Формируем результат
var result = new List<SearchResultItem>();
foreach (var fetch in fetched)
{
result.AddRange(fetch.Where(r => r.Quantity != 0));
}
return result;
}
示例9: Periodical
public IHttpActionResult Periodical(List<LabourPeriodical> periodicals)
{
periodicals.AsParallel().ForAll(x=>SmallQuoteEstimator.Australia.LabourEstimator.Periodical(x));
return Ok(new
{
data = periodicals
});
}
示例10: ParallelEncrypt
public static List<string> ParallelEncrypt(
List<string> data,
CancellationToken cancellationToken)
{
return data.AsParallel().WithCancellation(
cancellationToken).Select(
(item) => Encrypt(item)).ToList();
}
示例11: Crack
public string Crack(List<string> plaintext, string target)
{
var targetBytes = HexHelper.StringToByteArray(target);
ThreadLocal<MD5> md5 = new ThreadLocal<MD5>(() => MD5.Create());
var match = plaintext.AsParallel().Where(p => ByteArrayCompare(targetBytes, md5.Value.ComputeHash(Encoding.Default.GetBytes(p)))).FirstOrDefault();
return match;
}
示例12: ForAll
public List<int> ForAll ()
{
var myData = new List<int> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var ints = new List<int> ();
myData.AsParallel ().ForAll (x => ints.Add (x));
return ints;
}
示例13: WithNatural
public List<int> WithNatural ()
{
var myData = new List<int> () { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var data =
(from value in myData.AsParallel ()
select value);
return data.ToList ();
}
示例14: Equipment
public IHttpActionResult Equipment(List<EquipmentSupply> equipments)
{
equipments.AsParallel()
.ForAll(equipment => SmallQuoteEstimator.Australia.PriceEstimator.EquipmentPrice(equipment));
return Ok(new
{
data = equipments
});
}
示例15: ScanDirectory
public List<IisApplication> ScanDirectory(string directory)
{
#if ASYNC_TEST
Thread.Sleep(TimeSpan.FromSeconds(2));
#endif
var apps = new List<DirectoryInfo>();
AddWebAppDirs(directory, apps);
var result = apps.AsParallel().Select(GetApplicationInfo).ToList();
return result;
}