我试图使用值作为参考在列表中找到IndexOf。就像我们说Id = 23144一样,我想在输入Id时输入索引。 此对象列表是通过反序列化使用RestSharp检索的Json来生成的。
{
"not_modified_since":"2018-06-05T22:22:18Z",
"host":[
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"Redacted",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
]
}
我有以下代码:
private void bRun_Click(object sender, EventArgs e)
{
var client = new RestClient(endPoint);
var request = new RestRequest("/host/v14/by_id", Method.GET);
request.AddHeader("accept", "application/json");
request.AddHeader("Authorization", "Bearer " + key);
request.AddParameter("domain_id", "103947039");
request.AddParameter("ids", "195392183");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.RequestFormat = DataFormat.Json;
var response = client.Execute<RootObject>(request);
var rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content);
var hosts = rootObject.Host;
oResponse.Text = hosts.IndexOf();
}
可能有多个主机,因此我希望能够找到每个主机的索引,以便我可以知道哪一个检索遵循某些条件的值,例如那些与Id匹配的值。总而言之,我希望能够知道id 195392183在索引0处,这样我就可以使用该索引来检索名称的值(Broadsign Services - Mathias - 16x64)。
EDIT! 解决了!这对我有用:
var index = rootObject.Host.FindIndex(host => host.Id == 195392183);
答案 0 :(得分:0)
您可以根据主机
创建字典var hostsDict = rootObject.Select(r=> r.Host).ToDictionary<int, Host>(k=> k.Id, v=> v);
return hostDict[195392183];
答案 1 :(得分:0)
您可以使用自定义转换器为反序列化对象添加索引。
public class ListWithIndexConverter<T> : JsonConverter where T : IIndexedObject
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type != JTokenType.Array)
{
return new List<T>();
}
var returnList = new List<T>();
for(var i=0; i < token.Count(); i++)
{
var returnObject = token[i].ToObject<T>();
returnObject.Index = i;
returnList.Add(returnObject);
}
return returnList;
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public interface IIndexedObject
{
int Index { get; set; }
}
public class SomeObject
{
[JsonConverter(typeof(ListWithIndexConverter<Host>))]
public List<Host> Hosts { get; set; }
}
public class Host : IIndexedObject
{
//some properties
}