简体   繁体   English

将linq查询转换为通用字符串数组

[英]Convert linq query to Generic string array

I know that I can cast my linq query to an array or list but this doesn't seem to help. 我知道我可以将linq查询转换为数组或列表,但这似乎无济于事。

Here is my query: 这是我的查询:

  var bracct = from DataRow x in _checkMasterFileNew.Rows
    select new {BranchAccount = string.Format("{0}{1}", x["Branch"], x["AccountNumber"])};

When I attempt to convert it to a list or array: 当我尝试将其转换为列表或数组时:

  List<string> tstx = bracct.ToList();

or this: 或这个:

string[] stx = bracct.ToArray();

If give me this: 如果给我这个:

在此处输入图片说明

I am assuming I need to change my query but I'm not sure the best way to hanlde it. 我假设我需要更改查询,但是我不确定处理此问题的最佳方法。 How do I get it to a generic collection of strings? 如何获取通用字符串集合?

It won't work because you've created an anonymous type with 1 property which is a string. 这将不起作用,因为您已经创建了一个匿名类型,该匿名类型具有1个字符串属性。 Instead, If all you want is to convert it into a List<string> do: 相反,如果只想将其转换为List<string>请执行以下操作:

var bracct = (from DataRow x in _checkMasterFileNew.Rows
              select string.Format("{0}{1}", x["Branch"], x["AccountNumber"])).ToList();

And if using c# 6.0 you can use string interpolation: 如果使用c#6.0,则可以使用字符串插值:

var bracct = (from DataRow x in _checkMasterFileNew.Rows
              select $"{x["Branch"]}{x["AccountNumber"]}").ToList();

Your query is creating an anonymous type with a single member BranchAccount . 您的查询正在创建一个具有单个成员BranchAccount的匿名类型。 If you actually just want a string , then just select that instead: 如果您实际上只想要一个string ,那么只需选择它即可:

var bracct = 
    from DataRow x in _checkMasterFileNew.Rows
    select string.Format("{0}{1}", x["Branch"], x["AccountNumber"]);

And now your ToList() call will return List<string> : 现在,您的ToList()调用将返回List<string>

List<string> tstx = bracct.ToList();

You must select the property you are assigning the string to before performing ToList() , or remove the anonymous type and select string.Format() directly 在执行ToList()之前,必须选择要分配字符串的属性,或者删除匿名类型并直接select string.Format()

Try this: 尝试这个:

List<string> tstx = bracct.Select( x => x.BranchAccount ).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM