csharp 数组,列表,词典,Pocos

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 数组,列表,词典,Pocos相关的知识,希望对你有一定的参考价值。

/* pass the generic type as shown below */
Product modelFromDb = await _productManager.GetProductFirstOrDefault(productViewModel.Id);
var modelFromDbDict = ConvertModelClassToDictionary<Product>(modelFromDb);

/* if the model object is null, instantiate a null version of the Product type being passed  */
public static Dictionary<string, object> ConvertModelClassToDictionary<T>(object model)
{
  if (ReferenceEquals(null, model))
  {
    model = (T)Activator.CreateInstance(typeof(T), new object[] {});
  }
}

/******************************************************************************/

/* setting generic type's property value using reflection */
/* in this example; EmailApiResponse.ServerStatusCode is set to BadRequest */

public class EmailApiResponse {
  
  public HttpStatusCode ServerStatusCode { get; set; }
  
}

await PostToApiAsJson<EmailApiResponse>();

public static async Task<T> PostToApiAsJson<T>() {
  
  /* create an instance of the EmailApiResponse object  */
  var returnObj = (T)Activator.CreateInstance(typeof(T), new object[] { });
  
  /* set its ServerStatusCode property value */
  var serverStatusCode = typeof(T).GetProperty("ServerStatusCode");/* property name */
    if (serverStatusCode != null)
        serverStatusCode.SetValue(returnObj, HttpStatusCode.BadRequest, null);
        
}
for (int i = 0; i < Model.Insureds.Count; i++)
{
  var viewDataDict = new ViewDataDictionary
  {
    new KeyValuePair<string, object>("Prefix", "Insureds[" + i + "]"),
    new KeyValuePair<string, object>("EndorsementType", Model.EndorsementType.ToString()),
    new KeyValuePair<string, object>("InsuredId", Model.Insureds[i].Id)
  };
  @Html.Partial("_Insured", Model.Insureds[i], viewDataDict)
}
// Create a list of parts.
var parts = new List<Part>();
 
// Add parts to the list.
parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });

/*********************************************/

// Anonymous Type Lists
var modelType = typeof(SearchPolicyViewModel);
var modelData = ModelMetadataProviders.Current.GetMetadataForType(null, modelType);
    
var placeholders = new List<dynamic>();
foreach (var p in modelData.Properties)
{
  placeholders.Add(new { PropertyName = p.PropertyName, Placeholder = p.Watermark });
}

// Property name'i "SubeKod" olan list item'dan Placeholder degerini al.
var placeholder = placeholders.First(x => x.PropertyName == "SubeKod").Placeholder;

/* -- OR -- */
var factors = new List<dynamic> {new {Value = "", Text = ""}};

/*********************************************/

// Select columns from lists
var list = (await _store.GetAllPermissions()).Select(r =>
  {
      return
          new
          {
              id = r.Id.ToString(),
              text = r.Title,
              parent = !r.ParentId.HasValue ? "#" : r.ParentId.ToString(),
              state = new {selected = rolePermissions != null && rolePermissions.Any(rp => rp.Name.Equals(r.RecursiveName))},
              a_attr = new {showMenu = r.ShowMenu},
              icon = r.ShowMenu ? "" : "../assets/global/img/jstree-key.png"
          };
  });
  
/*********************************************/

// Convert list to comma separated string
  
Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));

/*********************************************/

// Convert list to queryable
var authList = new List<Auth>();
var q = authList.AsQueryable();
q = q.Where(e => e.RunInNewOffer);

/*********************************************/

// Modify anonymous list
var q = from cf in _productManager.GetAllCapFactors()
          join p in _productManager.GetAllProduct()
            on cf.ProductId equals p.Id
          join f in _productManager.GetAllFactors()
            on cf.FactorId equals f.Id
          select new
          {
            cf.Id,
            cf.FactorId,
            cf.ProductId,
            cf.CapUsage
          };

var capFactorQList = await q.ToListAsync();

var capFactorList = from cf in capFactorQList
select new
{
    cf.Id,
    ProductName = cf.ProductId + " - " + cf.ProductName,
    FactorName = cf.FactorId + " - " + cf.FactorName,
    CapUsageName = EnumHelper<CapUsageTypeEnum>.GetEnumDescription(cf.CapUsage)
};

/*********************************************/

// Get the Count of a List of unknown type
var selectData = from f in await GetAllFactorsList()
                   join pcf in distinctProductCoverageFactorsList
                      on f.Id equals pcf.FactorId
                   select new { f.Id, Text = f.DisplayName };

var selectDatalist = selectData.OrderBy(x => x.Id).ToList();
var selectDataIList = (IList) selectData;

if (selectDataIList != null && selectDataIList.Count > 0)
{
  resultDict = new Dictionary<string, object>
  {
    { "success", true },
    { "data", selectDatalist }
  };
}

/*********************************************/
var item = new KeyValueItem
{
  Foo = "Bee",
  Abc = "Scoo"
};
return Json(item);
var resultDict = new Dictionary<string, object>
{
  { "type", "error" },
  { "text", $"{rowIndex} nolu satırdaki kayıtta hata oluştu : {e.Message}" }
};
return Json(resultDict);

/* -- OR -- */

var resultDict = new Dictionary<string, string>();
resultDict.Add("Foo", "TTTDic");
resultDict.Add("Bar", "Scoo");
return Json(resultDict);

/*get value by key  */
String foo = Data_Array["Foo"];

/* Does it contain a key? */
if (resultDict.ContainsKey("Bar")) {
  
}

/* -------------------- */
/* LIST to DICTIONARY  */
var lookUpsDictionary = lookUpsList.ToDictionary(li => li.Id, li => li.Description);

/* -------------------- */
/* DICTIONARY to JSON   */
var lookUpsJson = JsonConvert.SerializeObject(lookUpsDictionary, Formatting.None);

以上是关于csharp 数组,列表,词典,Pocos的主要内容,如果未能解决你的问题,请参考以下文章

csharp 序列化词典时保留外壳

csharp 用于以所选元素阵列的词典顺序生成所有排列的扩展方法。

csharp [DataTable]到LINQ的数组列表

csharp 输出集合/列表/数组

搜索引擎基础概念—— 构建单词词典

数据结构词典