小编Sto*_*tip的帖子

避免C#数组中重复操作的最有效方法是什么?

我需要计算一个数组中每对点之间的距离,并且只想每对执行一次.我能提出足够的效率还是有更好的方法?这是一个例子,还有一个视觉来解释我想要获得的东西:

代码目的图

例如,首先得到段AB,AC,AD; 那么BC,BD; 最后,CD.换句话说,我们希望AB在我们的新阵列中,但不是BA,因为它将是重复.

var pointsArray = new Point[4];

pointsArray[0] = new Point(0, 0);
pointsArray[1] = new Point(10, 0);
pointsArray[2] = new Point(10, 10);
pointsArray[3] = new Point(0, 10);

// using (n * (n-1)) / 2 to determine array size
int distArraySize = (pointsArray.Length*(pointsArray.Length - 1))/2;

var distanceArray = new double[distArraySize];

int distanceArrayIndex = 0;

// Loop through points and get distances, never using same point pair twice
for (int currentPointIndex = 0; currentPointIndex < pointsArray.Length - 1; currentPointIndex++)
{ …
Run Code Online (Sandbox Code Playgroud)

c# arrays

11
推荐指数
1
解决办法
199
查看次数

为什么任务在执行下一个代码之前等待Task.Run而不是Task.Factory.StartNew?

至少当我在我的代码中实现它时,我不得不修改StartNew Task以获得相同的行为.在我的视图中有一个开始按钮.它的IsEnabled属性绑定到View Model中的Boolean.在不添加await task.ContinueWith(_ => true);return true;移出try块的情况下,PopulateListStartNew任务不会等待,因此按钮保持启用状态.我更喜欢使用,Task.Factory.StartNew因为传递TaskScheduler会产生更易读的代码(没有Dispatcher混乱).记录是一个ObservableCollection.

我认为Task.Run基本上是一个快捷方式(每个Task.Run vs Task.Factory.StartNew.无论如何,我想更好地理解行为上的差异,并且肯定会感谢任何有关使我的示例代码更好的建议.

public async Task<bool> PopulateListTaskRun(CancellationToken cancellationToken)
{
    try
    {
        await Task.Run(async () =>
            {
                // Clear the records out first, if any
                Application.Current.Dispatcher.InvokeAsync(() => Records.Clear());


                for (var i = 0; i < 10; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    // Resharper says do this to avoid "Access to modified closure"
                    var i1 = i;

                    Application.Current.Dispatcher.InvokeAsync(() =>
                        {
                            Records.Add(new Model
                                {
                                    Name = …
Run Code Online (Sandbox Code Playgroud)

c# wpf task-parallel-library async-await

2
推荐指数
1
解决办法
784
查看次数

这是确定何时返回所描述方案的空列表的好方法吗?

我有一个名为Division的类,它包含有关Subdivisions(在内部List中)的信息,包括每个细分的分类代码.在Subdivision类中,代码存储为int.在Division类中,List用于存储所有代码.有时会有一个没有细分的部门,因此没有代码.或者,无论出于何种原因,可能没有为细分设置代码.因此它的默认值为0.我不想返回列表,除非它有实际代码.

public List<int> AllCodesList
{
    get
    {
        return (from subdivision in SubdivisionInfoList
                where subdivision.code > 0 
                select subdivision.code).ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

c# linq getter list

0
推荐指数
1
解决办法
62
查看次数

标签 统计

c# ×3

arrays ×1

async-await ×1

getter ×1

linq ×1

list ×1

task-parallel-library ×1

wpf ×1