【问题标题】:Set property value while selecting from list of class objects从类对象列表中选择时设置属性值
【发布时间】:2021-10-17 09:07:05
【问题描述】:

我试图在从列表中选择时设置值(天值到“星期天”),如下面的方法“getData”,有没有一种方法可以在不真正改变类对象属性“天”值的情况下设置它?我只想在阅读时将其设置为“星期日”,例如将“星期日”设置为“日”。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleAppForChecking
{
    public class test
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
        public int age { get; set; }
        public string day { get; set; }
    }

    public class TestMain
    {
        static void Main(string[] args)
        {
            var tests = new List<test>()
            {
                new test { firstName = "Mike", lastName = "Toss", age = 20, day = "Monday" },
                new test { firstName = "Peter", lastName = "Page", age = 30, day = "Tuesday" },
                new test { firstName = "Stacy", lastName = "Page", age = 27, day = "Wednesday" }
            };

            getData(tests);
            GetDate(tests);
        }

        public static void getData(List<test> _data)
        {
            var _data1 = _data.Where(w => w.firstName == "Stacy")
                              .Select(o => new 
                                           { 
                                             o.firstName, 
                                             o.lastName, 
                                             day = o.day = "Sunday",
                                             o.age 
                                           })
                              .ToList();
            foreach(var d in _data1)
            {
                Console.WriteLine(d);
            }
        }

        public static void GetDate(List<test> _data1)
        {
            foreach (var d in _data1)
            {
                Console.WriteLine(d);
            }
        }
    }
}

【问题讨论】:

  • 我不太明白这个问题。你只想要day = "Sunday" 吗?在这种情况下,无需分配o.day,否则源对象的属性将被明确更改...
  • @OlivierRogier-我可以将天设置为星期日,但我不希望更改实际的类对象属性“天”值。我只想选择“星期日”作为“日”。类正在多个地方使用。
  • @.DeSon 因此,按照我写的去做。删除o.day =。运行新代码并查看它现在是否可以工作:查询显示使用 LINQ 创建的源集合中的所有新“克隆”对象的“星期天”,而源没有更改......这就是您要问的吗?
  • @OlivierRogier-啊!正确的。不知道我怎么弄不到。谢谢!
  • 是的:只要做你今天所做的事情 => new { MyFirstName = o.firstName, MyLastName = o.lastName, MyDay = "Sunday", MyAge = o.age })Linq 1Linq 2Deferred Execution of LINQ QueryLINQ (MSDocs)

标签: c# list linq


【解决方案1】:
_data.Where(w => w.firstName == "Stacy")
                              .Select(o=> {o.day = "Sunday"; return c;})
                              .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多