我是 c# 的新手,并将一些 python 重新编码为 c#。您将如何获取一个列表(list1)的范围并创建一个新的更短的列表(list2)?
python
list1= ["lets", "go", "visit", "houston", "texas"]
list2 = []
list2.append(list1[3:4]) ##new list is ["houston", "texas"]
#or
list2.append(list1[3:]) ##new list is ["houston", "texas"]
这在 c# 中看起来如何?
private void button1_Click(object sender, EventArgs e)
{
List < string > list1 = new List < string > ();
list1.Add("lets");
list1.Add("go");
list1.Add("visit")
list1.Add("houston");
list1.Add("texas");
List<string> list2 = list1.GetRange(3, 4);
}
有没有更好的方法来获取列表索引范围?以及如何开始索引,list1[:3] 或索引结束 list1[3:]
这将是 C# 等效项:
var list1 = new List<string> { "lets", "go", "visit", "houston", "texas" };
var list2 = new List<string>();
list2.AddRange(list1.Skip(3).Take(2 /* there is 2 elements from 3rd to 4th*/));
// or
list2.AddRange(list1.Skip(3));
编辑:您可以使用自定义方法扩展列表:
public static class ListExtensions
{
public static List<T> Slice<T>(this List<T> list, int? start = null, int? end = null)
{
if (start.HasValue)
return list.GetRange(start.Value, (end.HasValue ? (end.Value + 1) : list.Count) - start.Value);
if (end.HasValue) // not sure [:n] returns last n elements?
return list.GetRange(list.Count - end.Value, end.Value);
return list;
}
}
var list1 = new List<string> { "lets", "go", "visit", "houston", "texas" };
list1.Slice(3) // houston, texas
list1.Slice(3, 4) // houston, texas
list1.Slice(null, 3) // visit, houston, texas
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句