我可以从列表中选择单个项目吗?

时间:2014-04-24 06:59:59

标签: c# list indexing

我有一个字符串列表,我需要选择列表的某些部分来构造一个单独的字符串。我所拥有的是:

name,gender,haircolour,car;
or
John,Male,Brown,toyota;

我还有一个单独的文件,指明应该构造新字符串的部分和顺序。

例如:Index = 0,3,1会打印John,toyota,Male1,2,0会打印Male,Brown,John

我尝试了几种方法来尝试选择我想要的项目的索引,但所有返回值的函数只返回List的内容,唯一给出整数的返回值为Count(),我认为没有帮助。

我已经尝试过并尝试过,但我所做的一切都让自己越来越困惑。任何人都可以帮忙建议一种方法来实现这一目标吗?

3 个答案:

答案 0 :(得分:0)

如果我正确地理解了这个问题,那么这样的事情应该可以胜任:

const string data = "John,Male,Brown,toyota";
const string order = "0,3,1";

string[] indexes = order.Split(',');
string result = indexes.Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)] + ",");
result = result.TrimEnd(',');

如果您的字符串数据以分号';'结尾,正如您的问题中所示,则将该行更改为:

string result = indexes.Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)].TrimEnd(';') + ",");

请注意,此解决方案不会检查以确保给定数据字符串中存在给定索引。要添加一个检查以确保索引不会超过数组边界,请执行以下操作:

string result = indexes.Where(z => int.Parse(z) < data.Split(',').Length).Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)].TrimEnd(';') + ",");

答案 1 :(得分:0)

        List<string> list = new List<string> { "John", "Male", "Brown", "toyota" };
        List<int> indexList = new List<int> { 0, 3, 1 };
        List<string> resultList = new List<string>();
        indexList.ForEach(i => resultList.Add(list[i]));

答案 2 :(得分:0)

你应该能够做list [i],其中i是你需要的元素的索引。这里有一些例子:http://www.dotnetperls.com/list

相关问题