本文整理汇总了C#中List.ToArray方法的典型用法代码示例。如果您正苦于以下问题:C# List.ToArray方法的具体用法?C# List.ToArray怎么用?C# List.ToArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类List
的用法示例。
在下文中一共展示了List.ToArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
List<double> results;
List<double> modularity;
string line = "";
System.IO.File.Delete(Properties.Settings.Default.ResultFile);
for (double mod = Properties.Settings.Default.Modularity_From; mod <= Properties.Settings.Default.Modularity_To; mod += Properties.Settings.Default.Modularity_Step)
{
Console.WriteLine();
line = "";
for(double bias = Properties.Settings.Default.bias_from; bias <= Properties.Settings.Default.bias_to; bias += Properties.Settings.Default.bias_step)
{
results = new List<double>();
modularity = new List<double>();
System.Threading.Tasks.Parallel.For(0, Properties.Settings.Default.runs, j =>
{
ClusterNetwork net = new ClusterNetwork(Properties.Settings.Default.Nodes, Properties.Settings.Default.Edges, Properties.Settings.Default.Clusters, mod);
Console.WriteLine("Run {0}, created cluster network with modularity={1:0.00}", j, (net as ClusterNetwork).NewmanModularityUndirected);
/// TODO: Run experiment
});
line = string.Format(new CultureInfo("en-US").NumberFormat, "{0:0.000} {1:0.000} {2:0.000} {3:0.000} \t", MathNet.Numerics.Statistics.Statistics.Mean(modularity.ToArray()), bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()), MathNet.Numerics.Statistics.Statistics.StandardDeviation(results.ToArray()));
System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, line + "\n");
Console.WriteLine("Finished spreading on cluster network for modularity = {0:0.00}, bias = {1:0.00}, Average = {2:0.00}", mod, bias, MathNet.Numerics.Statistics.Statistics.Mean(results.ToArray()));
}
System.IO.File.AppendAllText(Properties.Settings.Default.ResultFile, "\n");
}
}
示例2: CreateActionDelegate
private Delegate CreateActionDelegate(MethodInfo method)
{
List<ParameterExpression> parameters = new List<ParameterExpression>();
foreach (ParameterInfo parameterInfo in method.GetParameters())
{
parameters.Add(Expression.Parameter(parameterInfo.ParameterType, parameterInfo.Name));
}
LambdaExpression lambda;
if (method.IsStatic)
{
lambda = Expression.Lambda(
GetActionType(parameters.Select(p => p.Type).ToArray()),
Expression.Call(method, parameters.Cast<Expression>().ToArray()),
parameters.ToArray());
}
else
{
Type bindingType = method.DeclaringType;
Expression<Func<object>> getInstanceExpression =
() => ScenarioContext.Current.GetBindingInstance(bindingType);
lambda = Expression.Lambda(
GetActionType(parameters.Select(p => p.Type).ToArray()),
Expression.Call(
Expression.Convert(getInstanceExpression.Body, bindingType),
method,
parameters.Cast<Expression>().ToArray()),
parameters.ToArray());
}
return lambda.Compile();
}
示例3: GetInvokeParametersForMethod
private static object[] GetInvokeParametersForMethod(MethodInfo methodInfo, IList<string> arguments)
{
var invokeParameters = new List<object>();
var args = new List<string>(arguments);
var methodParameters = methodInfo.GetParameters();
bool methodHasParams = false;
if (methodParameters.Length == 0) {
if (args.Count == 0)
return invokeParameters.ToArray();
return null;
}
if (methodParameters[methodParameters.Length - 1].ParameterType.IsAssignableFrom(typeof(string[]))) {
methodHasParams = true;
}
if (!methodHasParams && args.Count != methodParameters.Length) return null;
if (methodHasParams && (methodParameters.Length - args.Count >= 2)) return null;
for (int i = 0; i < args.Count; i++) {
if (methodParameters[i].ParameterType.IsAssignableFrom(typeof(string[]))) {
invokeParameters.Add(args.GetRange(i, args.Count - i).ToArray());
break;
}
invokeParameters.Add(Convert.ChangeType(arguments[i], methodParameters[i].ParameterType));
}
if (methodHasParams && (methodParameters.Length - args.Count == 1)) invokeParameters.Add(new string[] { });
return invokeParameters.ToArray();
}
示例4: ParseCPUTreeUsageInfo
internal static string ParseCPUTreeUsageInfo(List<string> processStrings, List<string> errorStrings)
{
if (processStrings.Count == 1) return processStrings[0];
if (errorStrings.Count > 0 && errorStrings.Exists(s => s.Contains("NoSuchProcess"))) throw new InvalidOperationException("Process could not be found. Output from CPU sampler is:"+string.Join(",", processStrings.ToArray()));
throw new ApplicationException(
string.Format("Could not process cpu snapshot output. StdOutput: {0}, ErrOutput: {1}", string.Join(",", processStrings.ToArray()), string.Join(",", errorStrings.ToArray())));
}
示例5: GetCompactedJavaScript
public static string GetCompactedJavaScript()
{
List<string> scripts = new List<string>();
foreach (string script in SiteUtility.Scripts)
{
scripts.Add(HttpContext.Current.Request.MapPath(script));
}
// set to expire cache when any of the source files changes
CacheDependency cacheDependency = new CacheDependency(scripts.ToArray());
Cache cache = HttpRuntime.Cache;
string cacheKey = "CompactedJavaScript";
if (cache[cacheKey] != null)
{
return cache[cacheKey] as string;
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("/* Generated " + DateTime.Now.ToUniversalTime().ToString("R", DateTimeFormatInfo.InvariantInfo) + " */\n");
sb.AppendLine(FileProcessor.Run(PackMode.JSMin, scripts.ToArray(), false));
string output = sb.ToString();
// hold for 30 minutes
cache.Insert(cacheKey, output, cacheDependency, DateTime.Now.AddMinutes(30),
Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
return output;
}
示例6: Create
internal static MethodInvoker Create(MethodInfo method, object target)
{
var args = new List<Type>(method.GetParameters().Select(p => p.ParameterType));
Type delegateType;
var returnMethodInvoker = new MethodInvoker
{
ParameterTypeList = args.ToList(),
ParameterCount = args.Count,
ReturnType = method.ReturnType,
MethodName = method.Name
};
if (method.ReturnType == typeof(void))
{
delegateType = Expression.GetActionType(args.ToArray());
}
else
{
args.Add(method.ReturnType);
delegateType = Expression.GetFuncType(args.ToArray());
}
returnMethodInvoker.MethodDelegate = method.CreateDelegate(delegateType, target);
return returnMethodInvoker;
}
示例7: GetAllFiles
private static string[] GetAllFiles(DirectoryInfo directory, string extension)
{
List<string> allFiles = new List<string>();
DirectoryInfo[] allDirectory = directory.GetDirectories();
if (allDirectory.Length > 0)
{
foreach (string[] files in allDirectory.Select(single => GetAllFiles(single, extension)))
{
allFiles.AddRange(files);
}
FileInfo[] fileInfos = directory.GetFiles();
allFiles.AddRange(from file in fileInfos
where file.Extension.ToLower().Equals(extension)
select file.FullName);
return allFiles.ToArray();
}
else
{
FileInfo[] files = directory.GetFiles();
allFiles.AddRange(from file in files
where file.Extension.ToLower().Equals(extension)
select file.FullName);
return allFiles.ToArray();
}
}
示例8: JsonObjectConstructorParmsTest
public void JsonObjectConstructorParmsTest()
{
JsonObject target = new JsonObject();
Assert.Equal(0, target.Count);
string key1 = AnyInstance.AnyString;
string key2 = AnyInstance.AnyString2;
JsonValue value1 = AnyInstance.AnyJsonValue1;
JsonValue value2 = AnyInstance.AnyJsonValue2;
List<KeyValuePair<string, JsonValue>> items = new List<KeyValuePair<string, JsonValue>>()
{
new KeyValuePair<string, JsonValue>(key1, value1),
new KeyValuePair<string, JsonValue>(key2, value2),
};
target = new JsonObject(items[0], items[1]);
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
target = new JsonObject(items.ToArray());
Assert.Equal(2, target.Count);
ValidateJsonObjectItems(target, key1, value1, key2, value2);
// Invalid tests
items.Add(new KeyValuePair<string, JsonValue>(key1, AnyInstance.DefaultJsonValue));
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items[0], items[1], items[2]); });
ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject(items.ToArray()); });
}
示例9: GetValueListFromJSONArray
public static string[] GetValueListFromJSONArray(string jsonString)
{
List<string> valueList = new List<string>();
if (string.IsNullOrEmpty(jsonString)
|| jsonString.Equals("null")
)
return valueList.ToArray();
try
{
JArray jo = JArray.Parse(jsonString);
foreach (JToken token in jo.Values())
{
if (token.Type == JsonTokenType.String)
valueList.Add(token.Value<string>().Trim());
}
}
catch (Exception e)
{
valueList.Add(jsonString);
return valueList.ToArray();
}
return valueList.ToArray();
}
示例10: ViewDidLoad
public override void ViewDidLoad()
{
base.ViewDidLoad ();
TKChart chart = new TKChart (this.ExampleBounds);
chart.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
this.View.AddSubview (chart);
Random r = new Random ();
List<CustomObject> data = new List<CustomObject> ();
for (int i = 0; i < 5; i++) {
CustomObject obj = new CustomObject () {
ObjectID = i,
Value1 = r.Next (100),
Value2 = r.Next (100),
Value3 = r.Next (100)
};
data.Add (obj);
}
chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value1"));
chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value2"));
chart.AddSeries (new TKChartAreaSeries (data.ToArray(), "ObjectID", "Value3"));
TKChartStackInfo stackInfo = new TKChartStackInfo (new NSNumber (1), TKChartStackMode.Stack);
for (int i = 0; i < chart.Series.Length; i++) {
TKChartSeries series = chart.Series [i];
series.SelectionMode = TKChartSeriesSelectionMode.Series;
series.StackInfo = stackInfo;
}
chart.ReloadData ();
}
示例11: GetModelQty
public ModelQty[] GetModelQty()
{
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
IList<ModelQty> ret = new List<ModelQty>();
DateTime now = new DateTime(2014, 1, 1);
Random rnd = new Random();
try
{
//1.检查传进来的参数
//Execute.ValidateParameter(CustSN);
//2.获取DB中的数据
//ModelResponse modelReponse = Execute.modelResponseMsg(CustSN);
//logger.DebugFormat("Reponse data:{0}", modelReponse.ToString());
for (int i = 0; i <= 100; ++i)
{
ret.Add(new ModelQty { Qty = rnd.Next(0, 200), Date = now.AddDays(i) });
}
return ret.ToArray();
}
catch (Exception e)
{
ret.Add(new ModelQty { Qty = 0, Date = now });
return ret.ToArray();
}
finally
{
}
}
示例12: FlashACard
public PartialViewResult FlashACard(string wantedDisplayDrug)
{
FlashDrugSetModel drugSetModel = new FlashDrugSetModel();
List<Drug> myBrandSearch = new DrugCardsRepository().GetDrugBrand(wantedDisplayDrug);
List<Drug> myGenericSearch = new DrugCardsRepository().GetDrugGeneric(wantedDisplayDrug);
drugSetModel.currentArrayIndex = 0;
List<string> resultInfo = new List<string>();
if (myBrandSearch.Count > 0 )
{
drugSetModel.currentDisplayDrug = myBrandSearch.First();
resultInfo.AddRange(myBrandSearch.Select(x => x.DrugBrand).ToList());
drugSetModel.userDrugInfoArray = resultInfo.ToArray();
}
else if(myGenericSearch.Count>0)
{
drugSetModel.currentDisplayDrug = myGenericSearch.First();
resultInfo.AddRange(myGenericSearch.Select(x => x.DrugBrand).ToList());
drugSetModel.userDrugInfoArray = resultInfo.ToArray();
}
return PartialView("_FlashMyCard", drugSetModel);
}
示例13: ToMaximumBytePackets
/// <summary>
/// Takes a list of metric strings, separating them with newlines into a byte packet of the maximum specified size.
/// </summary>
/// <param name="metrics"> The metrics to act on. </param>
/// <param name="packetSize"> Maximum size of each packet (512 bytes recommended for Udp). </param>
/// <returns> A streamed list of byte arrays, where each array is a maximum of 512 bytes. </returns>
public static IEnumerable<byte[]> ToMaximumBytePackets(this IEnumerable<string> metrics, int packetSize)
{
List<byte> packet = new List<byte>(packetSize);
foreach (string metric in metrics)
{
var bytes = Encoding.UTF8.GetBytes(metric);
if (packet.Count + _terminator.Length + bytes.Length <= packetSize)
{
packet.AddRange(bytes);
packet.AddRange(_terminator);
}
else if (bytes.Length >= packetSize)
{
yield return bytes;
}
else
{
yield return packet.ToArray();
packet.Clear();
packet.AddRange(bytes);
packet.AddRange(_terminator);
}
}
if (packet.Count > 0)
{
yield return packet.ToArray();
}
}
示例14: ProcessData
/// <summary>
/// Frame the incoming data and raise the OnFrameReceived when the lastBuffer holds at least a frame type in the frames to listen to list.
/// </summary>
public void ProcessData(byte[] bytes)
{
lastBuffer.AddRange(bytes.ToList());
List<byte> workingBuffer = new List<byte>();
//Get all the bytes that constitute a whole frame
var str = toStr(bytes);
while (lastBuffer.IndexOf(frameSeparator) > 0)
{
if (lastBuffer.Count > lastBuffer.IndexOf(frameSeparator))
workingBuffer = lastBuffer.Take(lastBuffer.IndexOf(frameSeparator) + 1).ToList();
else if (lastBuffer.Count == lastBuffer.IndexOf(frameSeparator))
workingBuffer = lastBuffer;
if (workingBuffer.Count() > 0)
{
foreach (var frame in Frames)
{
if (frame.IsFrameType(workingBuffer.ToArray()))
{
if (OnFrameReceived != null)
OnFrameReceived(frame.GetFrame(workingBuffer.ToArray()));
}
}
workingBuffer.Clear();
}
//Get the bytes from the last buffer that trail the last frame
if (lastBuffer.IndexOf(frameSeparator) + 1 == lastBuffer.Count)
lastBuffer.Clear();
else if (lastBuffer.IndexOf(frameSeparator) + 1 < lastBuffer.Count)
lastBuffer.RemoveRange(0, lastBuffer.IndexOf(frameSeparator) + 1);
}
}
示例15: Main
static void Main()
{
Solver solver = new Google.OrTools.ConstraintSolver.Solver("p");
// creating dummy variables
List<IntVar> vars = new List<IntVar>();
for (int i = 0; i < 200000; i++)
{
vars.Add(solver.MakeIntVar(0, 1));
}
IntExpr globalSum = solver.MakeSum(vars.ToArray());
DecisionBuilder db = solver.MakePhase(
vars.ToArray(),
Google.OrTools.ConstraintSolver.Solver.INT_VAR_SIMPLE,
Google.OrTools.ConstraintSolver.Solver.INT_VALUE_SIMPLE);
solver.NewSearch(db, new OptimizeVar(solver, true, globalSum.Var(), 100));
GC.Collect();
GC.WaitForPendingFinalizers();
while (solver.NextSolution())
{
Console.WriteLine("solution " + globalSum.Var().Value());
}
Console.WriteLine("fini");
Console.ReadLine();
}