我有一个文本文件,其中包含以下格式数据
I have a text file with below format data
[ { "SponsorID": 1, "FirstBAID": 7395836 }, { "SponsorID": 2, "FirstBAID": 3509279, "SecondBAID": 2947210 }, { "SponsorID": 3, "FirstBAID": 1776294, "SecondBAID": 6503843 }, { "SponsorID": 4, "FirstBAID": 8014528, "SecondBAID": 6203155 }, { "SponsorID": 5, "FirstBAID": 5968769, "SecondBAID": 7410195, "ThirdBAID":8950170, } ]我想将此数据读取为列表&那么我需要通过SponsorID进行查询. 我已经创建了一个像这样的类
I want to read this data as a List & then i need to query by SponsorID. I have created a class like this
public class SponsorInfo { public decimal SponsorID { get; set; } public decimal FirstBAID { get; set; } public decimal SecondBAID { get; set; } public decimal ThirdBAID { get; set; } }现在如何读取文本文件数据&绑定 SponsorInfo 类?
Now how can i read text file data & bind SponsorInfo class ?
推荐答案从NuGet程序包管理器控制台安装Newtonsoft.Json nuget程序包:
Install Newtonsoft.Json nuget package from NuGet package manager console:
PM> Install-Package Newtonsoft.Json然后:
var jsonText = File.ReadAllText("filepath"); var sponsors = JsonConvert.DeserializeObject<IList<SponsorInfo>>(jsonText);要在SponsorID上进行查询,可以使用LINQ:
To query on SponsorID you can use LINQ:
var sponsor5 = sponsors.FirstOrDefault(x => x.SponsorID == 5);如果您经常需要按SponsorID查找,则可以将结果转换为键为SponsorID的字典.这将提高性能,因为它不需要为每个查找都对整个列表进行枚举.我还建议您将SponsorID的类型更改为int而不是decimal.
If you often need a lookup by SponsorID, you could convert the result to a dictionary where the key is the SponsorID. This will improve performance as it doesn't need to enumerate through the entire list for each lookup. I also suggest you change the type of SponsorID to an int instead of a decimal.
var sponsorsById = sponsors.ToDictionary(x => x.SponsorID);然后,您可以像这样轻松地访问它:
Then you can easily access it like:
if (sponsorsById.ContainsKey(5)) var sponsor5 = sponsorsById[5];更多推荐
从文本文件C#中读取Json数据
发布评论