如何使用Linq向数组添加值? [英] How to add values to array using Linq?
本文介绍了如何使用Linq向数组添加值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用foreach循环添加到数组中。我想通过linq做同样的事。
我的代码如下:
foreach ( string SourceExcelFilePath in SourceExcelTemplateCollection)
{
// 从目标Excel模板(在DATA文件夹中)获取模板ID(如果有)以验证是否模板Id已存在
string SourceExcelTemplateName = Path.GetFileNameWithoutExtension(SourceExcelFilePath);
string [] SourceExcelTemplateId = SourceExcelTemplateName.Split(' _ 跨度>);
StdExcelTemplateIdList.Add(SourceExcelTemplateId [ 1 ]。ToString());
StdExcelTemplateIdValues = StdExcelTemplateIdList.ToArray();
}
解决方案
我的最佳镜头:
var result = SourceExcelTemplateCollection
.Select(x => new
{
SourceExcelTemplateId = Path.GetFileNameWithoutExtension(x) .Split(' _')[ 1 ]
});
它应该返回IEnumerable< string>
。要获取字符串的数组或列表,请使用ToArray()
或ToList( )
上述声明末尾的方法。
我怀疑你想实现类似这样的事情:
string [] SourceExcelTemplateCollection = new string [] { @ C: \Template_C012.xslt,
@ C:\Template_D511.xslt,
@ C:\Template_H914.xslt,
@ C:\Template_A011.xslt};
List< string> StdExcelTemplateIdList = SourceExcelTemplateCollection
.Select(x => Path.GetFileNameWithoutExtension(x).Split(' _' )[ 1 ])
.ToList< string>();
结果:
C012
D511
H914
A011
I am adding to array using the foreach loop. I want to do the same via linq.
My code is as below:
foreach (string SourceExcelFilePath in SourceExcelTemplateCollection)
{
//Fetch the Template Id from Destination Excel Template(In DATA Folder)if any to validate if Template Id already exists
string SourceExcelTemplateName = Path.GetFileNameWithoutExtension(SourceExcelFilePath);
string[] SourceExcelTemplateId = SourceExcelTemplateName.Split('_');
StdExcelTemplateIdList.Add(SourceExcelTemplateId[1].ToString());
StdExcelTemplateIdValues = StdExcelTemplateIdList.ToArray();
}
解决方案
My best shot:
var result = SourceExcelTemplateCollection .Select(x=>new { SourceExcelTemplateId = Path.GetFileNameWithoutExtension(x).Split('_')[1] });
It should returnIEnumerable<string>
. To get an array or a list of string, useToArray()
orToList()
method at the end of above statement.
[EDIT]
I suspect that you want to achieve something like this:
string[] SourceExcelTemplateCollection = new string[]{@"C:\Template_C012.xslt", @"C:\Template_D511.xslt", @"C:\Template_H914.xslt", @"C:\Template_A011.xslt"}; List<string> StdExcelTemplateIdList = SourceExcelTemplateCollection .Select(x=>Path.GetFileNameWithoutExtension(x).Split('_')[1]) .ToList<string>();
Result:
C012 D511 H914 A011
这篇关于如何使用Linq向数组添加值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文