具有重复键的自动排序列表c#

时间:2017-03-24 19:29:23

标签: c#

我有一系列对象和一个函数

double P(Object a, Object b){...}

现在,对于固定的对象a,我想以这种方式将所有其他对象存储在列表L中:

Objects a,b,c,d with P(a,b)=1, P(a,c)=2, P(a,d)=1 should have

L[0] = b or d, L[1] = b or d, L[2] = c

请注意,我只需要访问(不能修改,删除ecc ..)存储在L中的项目,如果L可以是SortedList,那么IndexOfValue将是完美的,但它不支持重复键。

有没有一种简单的方法可以解决这个问题?

1 个答案:

答案 0 :(得分:0)

来自c#交互式shell

// making up a class, since there aren't any details.
// make it have some kind of value, and a human friendly name
public class Thing { public int Val {get; set;} public string Name { get; set; } }

// since P isn't given, make something up. How about adding two numbers?
Func<Thing, Thing, double> P = (a, b) => { return a.Val + b.Val; };

// give starting values to match example function output
var a = new Thing() { Val = 0, Name = "a" };
var b = new Thing() { Val = 1, Name = "b" };
var c = new Thing() { Val = 2, Name = "c" };
var d = new Thing() { Val = 1, Name = "d" };

// others is the list of values, sorted by the output from the function "P",
// compared against the first Thing ("a" in this case")
var others = (new List<Thing>() { b,c,d }).OrderBy(x => P(a, x));

// interactive shell out gives: 
. others.Select(x => x.Name)
Enumerable.WhereSelectEnumerableIterator<Submission#0.Thing, string> { "b", "d", "c" }